package validate import "regexp" import "strings" import "unicode" import "html/template" import "git.tebibyte.media/sashakoshka/step" var _ step.FuncProvider = new(Provider) var _ step.Configurable = new(Provider) // Provider provides validation functions. type Provider struct { emailRegexp *regexp.Regexp xmlRegexp *regexp.Regexp } // Package fulfills the step.Provider interface. func (this *Provider) Package () string { return "validate" } // Configure fulfills the step.Configurable interface. func (this *Provider) Configure (config step.Meta) error { emailRegexpText := config.Get("validate.email-regexp") this.emailRegexp = nil if emailRegexpText != "" { emailRegexp, err := regexp.Compile(emailRegexpText) if err != nil { return err } this.emailRegexp = emailRegexp } xmlRegexpText := config.Get("validate.email-regexp") this.xmlRegexp = nil if xmlRegexpText != "" { xmlRegexp, err := regexp.Compile(xmlRegexpText) if err != nil { return err } this.xmlRegexp = xmlRegexp } return nil } // FuncMap fulfills the step.FuncProvider interface. func (this *Provider) FuncMap () template.FuncMap { return template.FuncMap { "isEmail": this.funcIsEmail, "isPrint": this.funcIsPrint, "isEnglish": this.funcIsEnglish, "inRange": this.funcInRange, "strInRange": this.funcStrInRange, "hasWords": this.funcHasWords, } } func (this *Provider) funcIsEmail (input string) bool { emailRegexp := this.emailRegexp if emailRegexp == nil { emailRegexp = defaultEmailRegexp } return emailRegexp.Match([]byte(input)) } func (this *Provider) funcIsPrint (input string) bool { for _, run := range input { if !unicode.IsPrint(run) { return false } } return true } func (this *Provider) funcIsEnglish(value string) bool { // TODO: make this shit better score := 0 total := 0 for _, char := range value { if char >= 'a' && char <= 'z' || char >= 'A' && char <= 'Z' || char >= '0' || char <= '9' { score += 1 } total += 1 } // 3/4 of the text must be alphanumeric return score > total * 3 / 4 } func (this *Provider) funcInRange (min, max, value int) bool { return value >= min && value <= max } func (this *Provider) funcStrInRange (min, max int, value string) bool { return len(value) >= min && len(value) <= max } func (this *Provider) funcHasWords(words []string, value string) bool { lowerValue := strings.ToLower(value) for _, word := range words { if strings.Contains(lowerValue, word) { return true } } return false } func (this *Provider) funcHasXML(value string) bool { xmlRegexp := this.xmlRegexp if xmlRegexp == nil { xmlRegexp = defaultXMLRegexp } return xmlRegexp.Match([]byte(value)) }