Documentation
¶
Overview ¶
Package validator implements value validations
Copyright 2014 Roberto Teixeira <robteix@robteix.com>
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Validator is a modification of https://github.com/go-validator/validator. It contains the following validation rules: - gte=4: tests whether a variable value is larger or equal to a given number. For number types, it's a simple greater-than test; for strings it tests the number of characters whereas for maps and slices it tests the number of items. - lte=4: tests whether a variable value is smaller or equal to a given number. For number types, it's a simple lesser-than test; for strings it tests the number of characters whereas for maps and slices it tests the number of items. - required: checks whether a variable is non-zero as defined by the golang spec. You're advised not to use this validation for booleans and numbers, - since golang defaults empty numbers to 0 and empty booleans to false. - name: string containing unicode letters -,.' and not start or end with a space. - az09_: string containing 0-9, A-Z, _ and not start with a _. - gender: string either "male", "female" or "genderqueer". - isodate: a time.Time where hour, minute, second and millisecond are 0. If value is a string checks if date is in YYYY-MM-DD format. - zoneinfo: zoneinfo timestamp, e.g. Europe/Amsterdam. - locale: space-separated string of BCP47 language tags. - mindate=2006-01-02: time.Time with a minimum date. "now" will use today's date. - maxdate=2006-01-02: time.Time with a maximum date "now" will use today's date. - url: accepts any url the golang request uri accepts. In addition the following tags are aliases: - username: "az09_,gte=4,lte=20" - birthdate: "isodate,mindate=1900-01-01,maxdate=now"
Index ¶
- Variables
- func AZ09(v interface{}, _ string) bool
- func AZ09Err(field string, _ interface{}, _ Tag) string
- func Az(v interface{}, _ string) bool
- func AzErr(field string, _ interface{}, _ Tag) string
- func Email(v interface{}, _ string) bool
- func EmailErr(field string, _ interface{}, _ Tag) string
- func Field(val interface{}, field string, tags string) error
- func Fields(errs ...error) error
- func GTE(v interface{}, param string) bool
- func GTEErr(field string, v interface{}, t Tag) string
- func Gender(v interface{}, _ string) bool
- func GenderErr(field string, _ interface{}, _ Tag) string
- func ISODate(v interface{}, _ string) bool
- func ISODateErr(field string, _ interface{}, _ Tag) string
- func LTE(v interface{}, param string) bool
- func LTEErr(field string, v interface{}, t Tag) string
- func Locale(v interface{}, _ string) bool
- func LocaleErr(field string, _ interface{}, _ Tag) string
- func MaxDate(v interface{}, param string) bool
- func MaxDateErr(field string, _ interface{}, t Tag) string
- func MinDate(v interface{}, param string) bool
- func MinDateErr(field string, _ interface{}, t Tag) string
- func Name(v interface{}, _ string) bool
- func NameErr(field string, _ interface{}, _ Tag) string
- func Optional(v interface{}, _ string) bool
- func RegexChecker(tagName string, match *regexp.Regexp, v interface{}) bool
- func Required(v interface{}, _ string) bool
- func RequiredErr(field string, _ interface{}, _ Tag) string
- func ResourceName(v interface{}, _ string) bool
- func ResourceNameErr(field string, _ interface{}, _ Tag) string
- func ResourcePattern(v interface{}, _ string) bool
- func ResourcePatternErr(field string, _ interface{}, _ Tag) string
- func Struct(value interface{}) error
- func URL(v interface{}, _ string) bool
- func URLErr(field string, _ interface{}, _ Tag) string
- func WithFullErrorPath() func(*Validator)
- func WithStandardAliases() func(*Validator)
- func WithStandardRules() func(*Validator)
- func Zoneinfo(v interface{}, _ string) bool
- func ZoneinfoErr(field string, _ interface{}, _ Tag) string
- type FieldError
- type FieldErrors
- type Option
- type RuleChecker
- type RuleErrorFunc
- type Tag
- type ValidationResult
- type ValidationRule
- type Validator
Constants ¶
This section is empty.
Variables ¶
var ( // InvalidTime can be set on a time.Time field to indicate parsing // the timestamp failed due to invalid formatting. InvalidTime = time.Unix(0, 0) StandardRules = []ValidationRule{ { Tag: "required", Checker: Required, ErrorFunc: RequiredErr, }, { Tag: "optional", Checker: Optional, ErrorFunc: nil, }, { Tag: "gte", Checker: GTE, ErrorFunc: GTEErr, }, { Tag: "lte", Checker: LTE, ErrorFunc: LTEErr, }, { Tag: "gender", Checker: Gender, ErrorFunc: GenderErr, }, { Tag: "isodate", Checker: ISODate, ErrorFunc: ISODateErr, }, { Tag: "mindate", Checker: MinDate, ErrorFunc: MinDateErr, }, { Tag: "maxdate", Checker: MaxDate, ErrorFunc: MaxDateErr, }, { Tag: "name", Checker: Name, ErrorFunc: NameErr, }, { Tag: "az_", Checker: Az, ErrorFunc: AzErr, }, { Tag: "aZ09_", Checker: AZ09, ErrorFunc: AZ09Err, }, { Tag: "zoneinfo", Checker: Zoneinfo, ErrorFunc: ZoneinfoErr, }, { Tag: "locale", Checker: Locale, ErrorFunc: LocaleErr, }, { Tag: "url", Checker: URL, ErrorFunc: URLErr, }, { Tag: "email", Checker: Email, ErrorFunc: EmailErr, }, { Tag: "resourcename", Checker: ResourceName, ErrorFunc: ResourceNameErr, }, { Tag: "resourcepattern", Checker: ResourcePattern, ErrorFunc: ResourcePatternErr, }, } StandardAliases = map[string]string{ "username": "aZ09_,gte=4,lte=20", "birthdate": "isodate,mindate=1900-01-01,maxdate=now", } )
var DefaultValidator = NewValidator( WithStandardRules(), WithStandardAliases())
var ( // ErrUnsupported is the error error returned when a validation rule // is used with an unsupported variable type. ErrUnsupported = errors.New("unsupported type") )
Functions ¶
func Field ¶
Field validates a value based on the provided tags. Returns the first error found or nil when valid.
func Fields ¶
Fields is a helper method to wrap a set of validate.Field() and returns a FieldErrors struct.
If you intend to add more errors you should consider using validate.NewResult() instead.
func GTE ¶
GTE tests whether a variable value is larger or equal to a given number. For number types, it's a simple greater-than test; for strings it tests the number of characters whereas for maps and slices it tests the number of items.
func ISODateErr ¶
func LTE ¶
LTE tests whether a variable value is smaller or equal to a given number. For number types, it's a simple lesser-than test; for strings it tests the number of characters whereas for maps and slices it tests the number of items.
func MaxDateErr ¶
func MinDateErr ¶
func Required ¶
Required tests whether a variable is non-zero as defined by the golang spec.
You're advised not to use this validation for booleans and numbers, since golang defaults empty numbers to 0 and empty booleans to false.
func RequiredErr ¶
func ResourceName ¶
func ResourceNameErr ¶
func ResourcePattern ¶
func ResourcePatternErr ¶
func Struct ¶
func Struct(value interface{}) error
Struct validates the fields of a struct based on the validator's tag and returns an array FieldErrors if one or more errors were found. Panics if value is not a struct.
func WithFullErrorPath ¶
func WithFullErrorPath() func(*Validator)
WithFullErrorPath adds the entire path in a struct or map to the field error.
func WithStandardAliases ¶
func WithStandardAliases() func(*Validator)
WithStandardRules adds the packaged tag aliases.
func WithStandardRules ¶
func WithStandardRules() func(*Validator)
WithStandardRules adds the packaged validation rules.
func ZoneinfoErr ¶
Types ¶
type FieldError ¶
FieldError contains an error message for a given field.
type FieldErrors ¶
type FieldErrors []FieldError
FieldErrors contains an array of errors returned by the validation functions.
func (FieldErrors) Error ¶
func (ve FieldErrors) Error() string
FieldErrors implements the Error interface and returns the first error as string if existent.
type RuleChecker ¶
RuleChecker is a function that receives the value of a field and a parameter used for the respective validation tag. Returns true when validation passed, or false if it didn't.
type RuleErrorFunc ¶
RuleErrorFunc returns an error message. This function is called when RuleChecker returned false.
type Tag ¶
type Tag struct { Name string Rule ValidationRule Param string }
type ValidationResult ¶
type ValidationResult struct {
Errors FieldErrors
}
ValidationResult is a collection of FieldErrors with helper methods.
func NewResult ¶
func NewResult(errs ...error) *ValidationResult
NewResult returns a ValidationResult with specified errors.
Use a ValidationResult to dynamically compose a set of validation errors.
func (*ValidationResult) AddError ¶
func (r *ValidationResult) AddError(err error)
AddError adds an error to the ValidationResult.
func (*ValidationResult) AddErrors ¶
func (r *ValidationResult) AddErrors(err ...error)
func (*ValidationResult) Error ¶
func (r *ValidationResult) Error() string
func (*ValidationResult) IsValid ¶
func (r *ValidationResult) IsValid() bool
IsValid returns false if one or more errors have been registered.
type ValidationRule ¶
type ValidationRule struct { // Tag is the struct tag to run this rule on. Tag string // Checker returns true when a value is valid, otherwise false. Checker RuleChecker // ErrorFunc is called when Checker returned false. The // ErrorFunc returns a proper error message. ErrorFunc RuleErrorFunc }
ValidationRule specifies the validation functions ("Checkers") and error message function ("ErrorFunc") for a given Tag.
The Checker and ErrorFunc are defined separately for more flexibility.
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator is the main validation construct.
func NewValidator ¶
NewValidator creates a new Validator with all default validation rules.
func (*Validator) AddAlias ¶
AddAlias adds a new alias or overwrites an existing one if alias already exists. Panics if one of the tags does not exist.
func (*Validator) AddRule ¶
func (mv *Validator) AddRule(rule ValidationRule)
AddRule adds a new rule or overwrites and existing rule if a rule with the same tag already exists.