63 lines
1.6 KiB
Go
63 lines
1.6 KiB
Go
package validate
|
|
|
|
import "regexp"
|
|
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
|
|
}
|
|
|
|
// 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
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// FuncMap fulfills the step.FuncProvider interface.
|
|
func (this *Provider) FuncMap () template.FuncMap {
|
|
return template.FuncMap {
|
|
"isEmail": this.funcIsEmail,
|
|
"isPrint": this.funcIsPrint,
|
|
"inRange": this.funcInRange,
|
|
"strInRange": this.funcStrInRange,
|
|
}
|
|
}
|
|
|
|
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) 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
|
|
}
|