validate

package
v0.0.0-...-9d149b6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 24, 2021 License: Apache-2.0 Imports: 11 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
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",
	}
)
View Source
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 AZ09

func AZ09(v interface{}, _ string) bool

func AZ09Err

func AZ09Err(field string, _ interface{}, _ Tag) string

func Az

func Az(v interface{}, _ string) bool

func AzErr

func AzErr(field string, _ interface{}, _ Tag) string

func Email

func Email(v interface{}, _ string) bool

func EmailErr

func EmailErr(field string, _ interface{}, _ Tag) string

func Field

func Field(val interface{}, field string, tags string) error

Field validates a value based on the provided tags. Returns the first error found or nil when valid.

func Fields

func Fields(errs ...error) error

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

func GTE(v interface{}, param string) bool

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 GTEErr

func GTEErr(field string, v interface{}, t Tag) string

func Gender

func Gender(v interface{}, _ string) bool

func GenderErr

func GenderErr(field string, _ interface{}, _ Tag) string

func ISODate

func ISODate(v interface{}, _ string) bool

func ISODateErr

func ISODateErr(field string, _ interface{}, _ Tag) string

func LTE

func LTE(v interface{}, param string) bool

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 LTEErr

func LTEErr(field string, v interface{}, t Tag) string

func Locale

func Locale(v interface{}, _ string) bool

func LocaleErr

func LocaleErr(field string, _ interface{}, _ Tag) string

func MaxDate

func MaxDate(v interface{}, param string) bool

func MaxDateErr

func MaxDateErr(field string, _ interface{}, t Tag) string

func MinDate

func MinDate(v interface{}, param string) bool

func MinDateErr

func MinDateErr(field string, _ interface{}, t Tag) string

func Name

func Name(v interface{}, _ string) bool

func NameErr

func NameErr(field string, _ interface{}, _ Tag) string

func Optional

func Optional(v interface{}, _ string) bool

Optional tests whether a variable is zero as defined by the golang spec.

func RegexChecker

func RegexChecker(tagName string, match *regexp.Regexp, v interface{}) bool

func Required

func Required(v interface{}, _ string) bool

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 RequiredErr(field string, _ interface{}, _ Tag) string

func ResourceName

func ResourceName(v interface{}, _ string) bool

func ResourceNameErr

func ResourceNameErr(field string, _ interface{}, _ Tag) string

func ResourcePattern

func ResourcePattern(v interface{}, _ string) bool

func ResourcePatternErr

func ResourcePatternErr(field string, _ interface{}, _ Tag) string

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 URL

func URL(v interface{}, _ string) bool

func URLErr

func URLErr(field string, _ interface{}, _ Tag) string

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 Zoneinfo

func Zoneinfo(v interface{}, _ string) bool

func ZoneinfoErr

func ZoneinfoErr(field string, _ interface{}, _ Tag) string

Types

type FieldError

type FieldError struct {
	Field       string
	Description string
}

FieldError contains an error message for a given field.

func (FieldError) Error

func (fe FieldError) Error() string

Error implements the Error interface.

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 Option

type Option func(*Validator)

Option allows functional options.

type RuleChecker

type RuleChecker func(v interface{}, param string) bool

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

type RuleErrorFunc func(field string, value interface{}, tag Tag) string

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) Err

func (r *ValidationResult) Err() error

Err returns FieldErrors.

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

func NewValidator(options ...Option) *Validator

NewValidator creates a new Validator with all default validation rules.

func (*Validator) AddAlias

func (mv *Validator) AddAlias(alias string, tags string)

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.

func (*Validator) Field

func (mv *Validator) Field(val interface{}, field string, tags string) error

Field validates a value based on the provided tags. Returns the first error found or nil when valid.

func (*Validator) Struct

func (mv *Validator) 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. Returns nil if no errors were found.

Panics if given value is not a struct.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL