Documentation ¶
Overview ¶
Package validate is a generic go data validate, filtering library.
Source code and other details for the project are available at GitHub:
https://github.com/gookit/validate
Index ¶
- Constants
- Variables
- func AddBuiltinMessages(mp map[string]string)
- func AddFilter(name string, filterFunc interface{})
- func AddFilters(m map[string]interface{})
- func AddGlobalMessages(mp map[string]string)
- func AddValidator(name string, checkFunc interface{})
- func AddValidators(m map[string]interface{})
- func AfterDate(srcDate, dstDate string) bool
- func AfterOrEqualDate(srcDate, dstDate string) bool
- func BeforeDate(srcDate, dstDate string) bool
- func BeforeOrEqualDate(srcDate, dstDate string) bool
- func Between(val interface{}, min, max int64) bool
- func BuiltinMessages() map[string]string
- func ByteLength(str string, minLen int, maxLen ...int) bool
- func CalcLength(val interface{}) int
- func CallByValue(fv reflect.Value, args ...interface{}) []reflect.Value
- func Config(fn func(opt *GlobalOption))
- func Contains(s, sub interface{}) bool
- func DateFormat(s string, layout string) bool
- func EndsWith(s, sub string) bool
- func Enum(val, enum interface{}) bool
- func Gt(val interface{}, dstVal int64) bool
- func HasLowerCase(s string) bool
- func HasURLSchema(s string) bool
- func HasUpperCase(s string) bool
- func HasWhitespace(s string) bool
- func IntEqual(val interface{}, wantVal int64) bool
- func IsASCII(s string) bool
- func IsAlpha(s string) bool
- func IsAlphaDash(s string) bool
- func IsAlphaNum(s string) bool
- func IsArray(val interface{}) (ok bool)
- func IsBase64(s string) bool
- func IsBool(val interface{}) bool
- func IsCIDR(s string) bool
- func IsCIDRv4(s string) bool
- func IsCIDRv6(s string) bool
- func IsCnMobile(s string) bool
- func IsDNSName(s string) bool
- func IsDataURI(s string) bool
- func IsDate(srcDate string) bool
- func IsDirPath(path string) bool
- func IsEmail(s string) bool
- func IsEmpty(val interface{}) bool
- func IsEqual(val, wantVal interface{}) bool
- func IsFilePath(path string) bool
- func IsFloat(val interface{}) bool
- func IsFullURL(s string) bool
- func IsHexColor(s string) bool
- func IsHexadecimal(s string) bool
- func IsIP(s string) bool
- func IsIPv4(s string) bool
- func IsIPv6(s string) bool
- func IsISBN10(s string) bool
- func IsISBN13(s string) bool
- func IsInt(val interface{}, minAndMax ...int64) (ok bool)
- func IsIntString(s string) bool
- func IsInts(val interface{}) bool
- func IsJSON(s string) bool
- func IsLatitude(s string) bool
- func IsLongitude(s string) bool
- func IsMAC(s string) bool
- func IsMap(val interface{}) (ok bool)
- func IsMultiByte(s string) bool
- func IsNumber(v interface{}) bool
- func IsNumeric(v interface{}) bool
- func IsPrintableASCII(s string) bool
- func IsRGBColor(s string) bool
- func IsSlice(val interface{}) (ok bool)
- func IsString(val interface{}, minAndMaxLen ...int) (ok bool)
- func IsStringNumber(s string) bool
- func IsStrings(val interface{}) (ok bool)
- func IsURL(s string) bool
- func IsUUID(s string) bool
- func IsUUID3(s string) bool
- func IsUUID4(s string) bool
- func IsUUID5(s string) bool
- func IsUint(val interface{}) bool
- func IsUnixPath(s string) bool
- func IsWinPath(s string) bool
- func IsZero(v reflect.Value) bool
- func Length(val interface{}, wantLen int) bool
- func Lt(val interface{}, dstVal int64) bool
- func Max(val interface{}, max int64) bool
- func MaxLength(val interface{}, maxLen int) bool
- func Min(val interface{}, min int64) bool
- func MinLength(val interface{}, minLen int) bool
- func NotContains(s, sub interface{}) bool
- func NotEqual(val, wantVal interface{}) bool
- func NotIn(val, enum interface{}) bool
- func PathExists(path string) bool
- func Regexp(str string, pattern string) bool
- func ResetOption()
- func RuneLength(val interface{}, minLen int, maxLen ...int) bool
- func StartsWith(s, sub string) bool
- func StringContains(s, sub string) bool
- func StringLength(val interface{}, minLen int, maxLen ...int) bool
- func ValidatorName(name string) string
- func Validators() map[string]int8
- func ValueIsEmpty(v reflect.Value) bool
- func ValueLen(v reflect.Value) int
- type ConfigValidationFace
- type CustomMessagesFace
- type DataFace
- type Errors
- func (es Errors) Add(field, validator, message string)
- func (es Errors) All() map[string]map[string]string
- func (es Errors) Empty() bool
- func (es Errors) Error() string
- func (es Errors) Field(field string) map[string]string
- func (es Errors) FieldOne(field string) string
- func (es Errors) HasField(field string) bool
- func (es Errors) One() string
- func (es Errors) Random() string
- func (es Errors) String() string
- type FieldTranslatorFace
- type FilterRule
- type FormData
- func (d *FormData) Add(key string, value string)
- func (d *FormData) AddFile(key string, file *multipart.FileHeader)
- func (d *FormData) AddFiles(filesMap map[string][]*multipart.FileHeader)
- func (d *FormData) AddValues(values url.Values)
- func (d FormData) Bool(key string) bool
- func (d *FormData) Create(err ...error) *Validation
- func (d *FormData) Del(key string)
- func (d *FormData) DelFile(key string)
- func (d *FormData) Encode() string
- func (d FormData) FileBytes(field string) ([]byte, error)
- func (d FormData) FileMimeType(field string) (mime string)
- func (d FormData) Float(key string) float64
- func (d FormData) Get(key string) (interface{}, bool)
- func (d FormData) GetFile(key string) *multipart.FileHeader
- func (d FormData) Has(key string) bool
- func (d FormData) HasField(key string) bool
- func (d FormData) HasFile(key string) bool
- func (d FormData) Int(key string) int
- func (d FormData) Int64(key string) int64
- func (d *FormData) Set(field string, val interface{}) (newVal interface{}, err error)
- func (d FormData) String(key string) string
- func (d FormData) Strings(key string) []string
- func (d *FormData) Type() uint8
- func (d *FormData) Validation(err ...error) *Validation
- type GlobalOption
- type M
- type MS
- type MapData
- func (d *MapData) BindJSON(ptr interface{}) error
- func (d *MapData) Create(err ...error) *Validation
- func (d *MapData) Get(field string) (interface{}, bool)
- func (d *MapData) Set(field string, val interface{}) (interface{}, error)
- func (d *MapData) Type() uint8
- func (d *MapData) Validation(err ...error) *Validation
- type MarshalFunc
- type NilObject
- type Rule
- func (r *Rule) Apply(v *Validation) (stop bool)
- func (r *Rule) Fields() []string
- func (r *Rule) SetBeforeFunc(fn func(v *Validation) bool)
- func (r *Rule) SetCheckFunc(checkFunc interface{}) *Rule
- func (r *Rule) SetFilterFunc(fn func(val interface{}) (interface{}, error)) *Rule
- func (r *Rule) SetMessage(errMsg string) *Rule
- func (r *Rule) SetMessages(msgMap MS) *Rule
- func (r *Rule) SetOptional(optional bool)
- func (r *Rule) SetScene(scene string) *Rule
- func (r *Rule) SetSkipEmpty(skipEmpty bool)
- type Rules
- type SValues
- type StructData
- func (d *StructData) Create(err ...error) *Validation
- func (d *StructData) FuncValue(name string) (reflect.Value, bool)
- func (d *StructData) Get(field string) (interface{}, bool)
- func (d *StructData) HasField(field string) bool
- func (d *StructData) Set(field string, val interface{}) (newVal interface{}, err error)
- func (d *StructData) Type() uint8
- func (d *StructData) Validation(err ...error) *Validation
- type Translator
- func (t *Translator) AddFieldMap(fieldMap map[string]string)
- func (t *Translator) AddMessage(key, msg string)
- func (t *Translator) AddMessages(data map[string]string)
- func (t *Translator) FieldMap() map[string]string
- func (t *Translator) HasField(field string) bool
- func (t *Translator) HasMessage(key string) bool
- func (t *Translator) Message(validator, field string, args ...interface{}) (msg string)
- func (t *Translator) Reset()
- type UnmarshalFunc
- type Validation
- func JSON(s string, scene ...string) *Validation
- func Map(m map[string]interface{}, scene ...string) *Validation
- func New(data interface{}, scene ...string) *Validation
- func NewEmpty(scene ...string) *Validation
- func NewValidation(data DataFace, scene ...string) *Validation
- func Request(r *http.Request) *Validation
- func Struct(s interface{}, scene ...string) *Validation
- func (v *Validation) AddError(field, validator, msg string)
- func (v *Validation) AddErrorf(field, msgFormat string, args ...interface{})
- func (v *Validation) AddFilter(name string, filterFunc interface{})
- func (v *Validation) AddFilters(m map[string]interface{})
- func (v *Validation) AddMessages(m map[string]string)
- func (v *Validation) AddRule(fields, validator string, args ...interface{}) *Rule
- func (v *Validation) AddTranslates(m map[string]string)
- func (v *Validation) AddValidator(name string, checkFunc interface{})
- func (v *Validation) AddValidators(m map[string]interface{})
- func (v *Validation) AppendRule(rule *Rule) *Rule
- func (v *Validation) AtScene(scene string) *Validation
- func (v *Validation) BindSafeData(ptr interface{}) error
- func (v *Validation) BindStruct(ptr interface{}) error
- func (v *Validation) ConfigRules(mp MS) *Validation
- func (v *Validation) EqField(val interface{}, dstField string) bool
- func (v *Validation) FilterFuncValue(name string) reflect.Value
- func (v *Validation) FilterRule(field string, rule string) *FilterRule
- func (v *Validation) FilterRules(rules map[string]string) *Validation
- func (v *Validation) Filtered(key string) interface{}
- func (v *Validation) FilteredData() M
- func (v *Validation) Filtering() bool
- func (v *Validation) Get(key string) (interface{}, bool)
- func (v *Validation) GetDefValue(field string) (interface{}, bool)
- func (v *Validation) GetSafe(key string) interface{}
- func (v *Validation) GetWithDefault(key string) (val interface{}, exist, isDefault bool)
- func (v *Validation) GtField(val interface{}, dstField string) bool
- func (v *Validation) GteField(val interface{}, dstField string) bool
- func (v *Validation) HasValidator(name string) bool
- func (v *Validation) InMimeTypes(fd *FormData, field, mimeType string, moreTypes ...string) bool
- func (v *Validation) InScene(scene string) *Validation
- func (v *Validation) IsFail() bool
- func (v *Validation) IsFormFile(fd *FormData, field string) (ok bool)
- func (v *Validation) IsFormImage(fd *FormData, field string, exts ...string) (ok bool)
- func (v *Validation) IsOK() bool
- func (v *Validation) IsSuccess() bool
- func (v *Validation) LtField(val interface{}, dstField string) bool
- func (v *Validation) LteField(val interface{}, dstField string) bool
- func (v *Validation) NeField(val interface{}, dstField string) bool
- func (v *Validation) Raw(key string) (interface{}, bool)
- func (v *Validation) Required(field string, val interface{}) bool
- func (v *Validation) RequiredIf(field string, val interface{}, kvs ...string) bool
- func (v *Validation) RequiredUnless(_ string, val interface{}, kvs ...string) bool
- func (v *Validation) RequiredWith(_ string, val interface{}, kvs ...string) bool
- func (v *Validation) RequiredWithAll(_ string, val interface{}, kvs ...string) bool
- func (v *Validation) RequiredWithout(_ string, val interface{}, kvs ...string) bool
- func (v *Validation) RequiredWithoutAll(_ string, val interface{}, kvs ...string) bool
- func (v *Validation) Reset()
- func (v *Validation) ResetResult()
- func (v *Validation) Safe(key string) (val interface{}, ok bool)
- func (v *Validation) SafeData() M
- func (v *Validation) SafeVal(key string) interface{}
- func (v *Validation) Sanitize() bool
- func (v *Validation) Scene() string
- func (v *Validation) SceneFields() []string
- func (v *Validation) Set(field string, val interface{}) error
- func (v *Validation) SetDefValue(field string, val interface{})
- func (v *Validation) SetScene(scene ...string) *Validation
- func (v *Validation) StringRule(field, rule string, filterRule ...string) *Validation
- func (v *Validation) StringRules(mp MS) *Validation
- func (v *Validation) Trans() *Translator
- func (v *Validation) Validate(scene ...string) bool
- func (v *Validation) ValidateData(data DataFace) bool
- func (v *Validation) Validators(withGlobal bool) map[string]int8
- func (v *Validation) WithError(err error) *Validation
- func (v *Validation) WithMessages(m map[string]string) *Validation
- func (v *Validation) WithScenarios(scenes SValues) *Validation
- func (v *Validation) WithScenes(scenes map[string][]string) *Validation
- func (v *Validation) WithTranslates(m map[string]string) *Validation
Examples ¶
Constants ¶
const ( Email = `` /* 150-byte string literal not displayed */ UUID3 = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$" UUID4 = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" UUID5 = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" UUID = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" Int = "^(?:[-+]?(?:0|[1-9][0-9]*))$" Float = "^(?:[-+]?(?:[0-9]+))?(?:\\.[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$" RGBColor = "" /* 157-byte string literal not displayed */ FullWidth = "[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]" HalfWidth = "[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]" Base64 = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$" Latitude = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$" Longitude = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$" DNSName = `^([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*[\._]?$` FullURL = `^(?:ftp|tcp|udp|wss?|https?):\/\/[\w\.\/#=?&]+$` URLSchema = `((ftp|tcp|udp|wss?|https?):\/\/)` URLUsername = `(\S+(:\S*)?@)` URLPath = `((\/|\?|#)[^\s]*)` URLPort = `(:(\d{1,5}))` URLIP = `([1-9]\d?|1\d\d|2[01]\d|22[0-3])(\.(1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))` URLSubdomain = `((www\.)|([a-zA-Z0-9]+([-_\.]?[a-zA-Z0-9])*[a-zA-Z0-9]\.[a-zA-Z0-9]+))` WinPath = `^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$` UnixPath = `^(/[^/\x00]*)+/?$` )
Basic regular expressions for validating strings. (there are from package "asaskevich/govalidator")
Variables ¶
var ( Marshal MarshalFunc = json.Marshal Unmarshal UnmarshalFunc = json.Unmarshal )
data (Un)marshal func
var ( ErrSetValue = errors.New("set value failure") // ErrNoData = errors.New("validate: no any data can be collected") ErrNoField = errors.New("field not exist in the source data") ErrEmptyData = errors.New("please input data use for validate") ErrInvalidData = errors.New("invalid input data") )
some internal error definition
Functions ¶
func AddBuiltinMessages ¶ added in v1.2.1
AddBuiltinMessages alias of the AddGlobalMessages()
func AddFilter ¶
func AddFilter(name string, filterFunc interface{})
AddFilter add global filter to the pkg.
func AddGlobalMessages ¶ added in v1.2.3
AddGlobalMessages add global builtin messages
func AddValidator ¶
func AddValidator(name string, checkFunc interface{})
AddValidator to the pkg. checkFunc must return a bool Usage:
v.AddValidator("myFunc", func(val interface{}) bool { // do validate val ... return true })
func AddValidators ¶
func AddValidators(m map[string]interface{})
AddValidators to the global validators map
func BeforeOrEqualDate ¶
BeforeOrEqualDate check
func BuiltinMessages ¶ added in v1.2.1
BuiltinMessages get builtin messages
func ByteLength ¶
ByteLength check string's length
func CallByValue ¶
CallByValue call func by reflect.Value
func Contains ¶
func Contains(s, sub interface{}) bool
Contains check that the specified string, list(array, slice) or map contains the specified substring or element.
Notice: list check value exist. map check key exist.
func Enum ¶
func Enum(val, enum interface{}) bool
Enum value(int(X),string) should be in the given enum(strings, ints, uints).
func HasLowerCase ¶ added in v1.0.3
HasLowerCase check string has lower case
func HasUpperCase ¶ added in v1.0.3
HasUpperCase check string has upper case
func IsCIDR ¶
IsCIDR is the validation function for validating if the field's value is a valid v4 or v6 CIDR address.
func IsCIDRv4 ¶
IsCIDRv4 is the validation function for validating if the field's value is a valid v4 CIDR address.
func IsCIDRv6 ¶
IsCIDRv6 is the validation function for validating if the field's value is a valid v6 CIDR address.
func IsDataURI ¶
IsDataURI string. data:[<mime type>] ( [;charset=<charset>] ) [;base64],码内容 eg. "data:image/gif;base64,R0lGODlhA..."
func IsEqual ¶
func IsEqual(val, wantVal interface{}) bool
IsEqual check two value is equals. Support:
bool, int(X), uint(X), string, float(X) AND slice, array, map
func IsIP ¶
IsIP is the validation function for validating if the field's value is a valid v4 or v6 IP address.
func IsIPv6 ¶
IsIPv6 is the validation function for validating if the field's value is a valid v6 IP address.
func IsMAC ¶
IsMAC is the validation function for validating if the field's value is a valid MAC address.
func IsNumeric ¶ added in v1.2.0
func IsNumeric(v interface{}) bool
IsNumeric is string/int number. should >= 0
func IsString ¶
IsString check and support length check. Usage:
ok := IsString(val) ok := IsString(val, 5) // with min len check ok := IsString(val, 5, 12) // with min and max len check
func IsStringNumber ¶ added in v1.2.0
IsStringNumber is string number. should >= 0
func IsZero ¶ added in v1.2.0
IsZero reports whether v is the zero value for its type. It panics if the argument is invalid. NOTICE: this's an built-in method in reflect/value.go since go 1.13
func Min ¶
Min check value greater or equal dst value, alias `Gte`. only check for: int(X), uint(X), float(X).
func NotContains ¶
func NotContains(s, sub interface{}) bool
NotContains check that the specified string, list(array, slice) or map does NOT contain the specified substring or element.
Notice: list check value exist. map check key exist.
func NotIn ¶
func NotIn(val, enum interface{}) bool
NotIn value should be not in the given enum(strings, ints, uints).
func PathExists ¶ added in v1.2.0
PathExists reports whether the named file or directory exists.
func RuneLength ¶
RuneLength check string's length (including multi byte strings)
func StartsWith ¶ added in v1.2.0
StartsWith check string is starts with sub-string
func StringContains ¶ added in v1.2.0
StringContains check string is contains sub-string
func StringLength ¶
StringLength check string's length (including multi byte strings)
Types ¶
type ConfigValidationFace ¶
type ConfigValidationFace interface {
ConfigValidation(v *Validation)
}
ConfigValidationFace definition. you can do something on create Validation.
type CustomMessagesFace ¶
CustomMessagesFace definition. you can custom validator error messages. Usage:
type User struct { Name string `json:"name" validate:"required|minLen:5"` } func (u *User) Messages() map[string]string { return MS{ "Name.required": "oh! User name is required", } }
type DataFace ¶
type DataFace interface { Type() uint8 Get(key string) (interface{}, bool) Set(field string, val interface{}) (interface{}, error) // validation instance create func Create(err ...error) *Validation Validation(err ...error) *Validation }
DataFace data source interface definition
current has three data source: - map - form - struct
type Errors ¶
Errors validate errors definition Example:
{ "field": {validator: message, validator1: message1} }
type FieldTranslatorFace ¶
FieldTranslatorFace definition. you can custom field translates. Usage:
type User struct { Name string `json:"name" validate:"required|minLen:5"` } func (u *User) Translates() map[string]string { return MS{ "Name": "User name", } }
type FilterRule ¶
type FilterRule struct {
// contains filtered or unexported fields
}
FilterRule definition
func (*FilterRule) AddFilters ¶
func (r *FilterRule) AddFilters(filters ...string) *FilterRule
AddFilters add filter(s). Usage:
r.AddFilters("int", "str2arr:,")
func (*FilterRule) Apply ¶
func (r *FilterRule) Apply(v *Validation) (err error)
Apply rule for the rule fields
type FormData ¶
type FormData struct { // Form holds any basic key-value string data // This includes all fields from urlencoded form, // and the form fields only (not files) from a multipart form Form url.Values // Files holds files from a multipart form only. // For any other type of request, it will always // be empty. Files only supports one file per key, // since this is by far the most common use. If you // need to have more than one file per key, parse the // files manually using r.MultipartForm.File. Files map[string]*multipart.FileHeader // contains filtered or unexported fields }
FormData obtained from the request body or url query parameters or user custom setting.
func FromURLValues ¶
FromURLValues build data instance.
func (*FormData) Add ¶
Add adds the value to key. It appends to any existing values associated with key.
func (*FormData) AddFile ¶
func (d *FormData) AddFile(key string, file *multipart.FileHeader)
AddFile adds the multipart form file to data with the given key.
func (*FormData) AddFiles ¶
func (d *FormData) AddFiles(filesMap map[string][]*multipart.FileHeader)
AddFiles adds the multipart form files to data
func (*FormData) Create ¶
func (d *FormData) Create(err ...error) *Validation
Create a Validation from data
func (*FormData) DelFile ¶
DelFile deletes the file associated with key (if any). If there is no file associated with key, it does nothing.
func (*FormData) Encode ¶
Encode encodes the values into “URL encoded” form ("bar=baz&foo=quux") sorted by key. Any files in d will be ignored because there is no direct way to convert a file to a URL encoded value.
func (FormData) FileBytes ¶
FileBytes returns the body of the file associated with key. If there is no file associated with key, it returns nil (not an error). It may return an error if there was a problem reading the file. If you need to know whether or not the file exists (i.e. whether it was provided in the request), use the FileExists method.
func (FormData) FileMimeType ¶
FileMimeType get File Mime Type name. eg "image/png"
func (FormData) GetFile ¶
func (d FormData) GetFile(key string) *multipart.FileHeader
GetFile returns the multipart form file associated with key, if any, as a *multipart.FileHeader. If there is no file associated with key, it returns nil. If you just want the body of the file, use GetFileBytes.
func (FormData) HasField ¶
HasField returns true iff data.Form[key] exists. When parsing a request body, the key is considered to be in existence if it was provided in the request body, even if its value is empty.
func (FormData) HasFile ¶
HasFile returns true iff data.Files[key] exists. When parsing a request body, the key is considered to be in existence if it was provided in the request body, even if the file is empty.
func (*FormData) Validation ¶
func (d *FormData) Validation(err ...error) *Validation
Validation create from data
type GlobalOption ¶
type GlobalOption struct { // FilterTag name in the struct tags. FilterTag string // ValidateTag in the struct tags. ValidateTag string // FieldTag name in the struct tags. for define field translate. default: json FieldTag string // MessageTag define error message for the field. MessageTag string // StopOnError If true: An error occurs, it will cease to continue to verify StopOnError bool // SkipOnEmpty Skip check on field not exist or value is empty SkipOnEmpty bool // UpdateSource Whether to update source field value, useful for struct validate UpdateSource bool // CheckDefault Whether to validate the default value set by the user CheckDefault bool // CheckZero Whether validate the default zero value. (intX,uintX: 0, string: "") CheckZero bool }
GlobalOption settings for validate
type MapData ¶
type MapData struct { // Map the source map data Map map[string]interface{} // contains filtered or unexported fields }
MapData definition
func FromJSONBytes ¶
FromJSONBytes string build data instance.
func (*MapData) BindJSON ¶
BindJSON binds v to the JSON data in the request body. It calls json.Unmarshal and sets the value of v.
func (*MapData) Create ¶
func (d *MapData) Create(err ...error) *Validation
Create a Validation from data
func (*MapData) Validation ¶
func (d *MapData) Validation(err ...error) *Validation
Validation create from data
type NilObject ¶ added in v1.1.1
type NilObject struct{}
NilObject represent nil value for calling functions and should be reflected at custom filters as nil variable.
type Rule ¶
type Rule struct {
// contains filtered or unexported fields
}
Rule definition
func (*Rule) Apply ¶
func (r *Rule) Apply(v *Validation) (stop bool)
Apply current rule for the rule fields
func (*Rule) SetBeforeFunc ¶
func (r *Rule) SetBeforeFunc(fn func(v *Validation) bool)
SetBeforeFunc for the rule. will call it before validate.
func (*Rule) SetCheckFunc ¶
SetCheckFunc set custom validate func.
func (*Rule) SetFilterFunc ¶
SetFilterFunc for the rule
func (*Rule) SetMessage ¶
SetMessage set error message. Usage:
v.AddRule("name", "required").SetMessage("error message")
func (*Rule) SetMessages ¶
SetMessages set error message map. Usage:
v.AddRule("name,email", "required").SetMessages(MS{ "name": "error message 1", "email": "error message 2", })
func (*Rule) SetOptional ¶
SetOptional only validate on value is not empty.
func (*Rule) SetSkipEmpty ¶
SetSkipEmpty skip validate not exist field/empty value
type StructData ¶
type StructData struct { // FieldTag name in the struct tags. for define filed translate FieldTag string // MessageTag define error message for the field. MessageTag string // FilterTag name in the struct tags. FilterTag string // ValidateTag name in the struct tags. ValidateTag string // contains filtered or unexported fields }
StructData definition
func FromStruct ¶
func FromStruct(s interface{}) (*StructData, error)
FromStruct create a Data from struct
func (*StructData) Create ¶
func (d *StructData) Create(err ...error) *Validation
Validation create from the StructData
func (*StructData) FuncValue ¶
func (d *StructData) FuncValue(name string) (reflect.Value, bool)
FuncValue get func value in the src struct
func (*StructData) Get ¶
func (d *StructData) Get(field string) (interface{}, bool)
Get value by field name
func (*StructData) HasField ¶
func (d *StructData) HasField(field string) bool
HasField in the src struct
func (*StructData) Set ¶
func (d *StructData) Set(field string, val interface{}) (newVal interface{}, err error)
Set value by field name. Notice: `StructData.src` the incoming struct must be a pointer to set the value
func (*StructData) Validation ¶
func (d *StructData) Validation(err ...error) *Validation
Create a Validation from the StructData
type Translator ¶
type Translator struct {
// contains filtered or unexported fields
}
Translator definition
func (*Translator) AddFieldMap ¶
func (t *Translator) AddFieldMap(fieldMap map[string]string)
AddFieldMap config field data. If you want to display in the field with the original field is not the same
func (*Translator) AddMessage ¶
func (t *Translator) AddMessage(key, msg string)
AddMessage to translator
func (*Translator) AddMessages ¶ added in v1.2.0
func (t *Translator) AddMessages(data map[string]string)
AddMessages data to translator
func (*Translator) HasField ¶
func (t *Translator) HasField(field string) bool
HasField name in the t.fieldMap
func (*Translator) HasMessage ¶
func (t *Translator) HasMessage(key string) bool
HasMessage key in the t.messages
func (*Translator) Message ¶
func (t *Translator) Message(validator, field string, args ...interface{}) (msg string)
Message get by validator name and field name.
type Validation ¶
type Validation struct { // Errors for the validate Errors Errors // CacheKey for cache rules // CacheKey string // StopOnError If true: An error occurs, it will cease to continue to verify StopOnError bool // SkipOnEmpty Skip check on field not exist or value is empty SkipOnEmpty bool // UpdateSource Whether to update source field value, useful for struct validate UpdateSource bool // CheckDefault Whether to validate the default value set by the user CheckDefault bool // contains filtered or unexported fields }
Validation definition
func JSON ¶
func JSON(s string, scene ...string) *Validation
JSON create validation from JSON string.
func New ¶
func New(data interface{}, scene ...string) *Validation
New create a Validation instance data support: - DataFace - M/map[string]interface{} - SValues/url.Values/map[string][]string - struct ptr
func NewEmpty ¶ added in v1.0.2
func NewEmpty(scene ...string) *Validation
NewEmpty new validation instance, but not add data.
func NewValidation ¶
func NewValidation(data DataFace, scene ...string) *Validation
NewValidation new validation instance
func Struct ¶
func Struct(s interface{}, scene ...string) *Validation
Struct validation create
Example ¶
u := &UserForm{ Name: "inhere", } v := Struct(u) ok := v.Validate() fmt.Println(ok)
Output:
func (*Validation) AddError ¶
func (v *Validation) AddError(field, validator, msg string)
AddError message for a field
func (*Validation) AddErrorf ¶
func (v *Validation) AddErrorf(field, msgFormat string, args ...interface{})
AddErrorf add a formatted error message
func (*Validation) AddFilter ¶
func (v *Validation) AddFilter(name string, filterFunc interface{})
AddFilter to the Validation.
func (*Validation) AddFilters ¶
func (v *Validation) AddFilters(m map[string]interface{})
AddFilters to the Validation
func (*Validation) AddMessages ¶
func (v *Validation) AddMessages(m map[string]string)
AddMessages settings data. like WithMessages()
func (*Validation) AddRule ¶
func (v *Validation) AddRule(fields, validator string, args ...interface{}) *Rule
AddRule for current validation
func (*Validation) AddTranslates ¶
func (v *Validation) AddTranslates(m map[string]string)
AddTranslates settings data. like WithTranslates()
func (*Validation) AddValidator ¶
func (v *Validation) AddValidator(name string, checkFunc interface{})
AddValidator to the Validation. checkFunc must return a bool. Usage:
v.AddValidator("myFunc", func(val interface{}) bool { // do validate val ... return true })
func (*Validation) AddValidators ¶
func (v *Validation) AddValidators(m map[string]interface{})
AddValidators to the Validation
func (*Validation) AppendRule ¶
func (v *Validation) AppendRule(rule *Rule) *Rule
AppendRule instance
func (*Validation) AtScene ¶
func (v *Validation) AtScene(scene string) *Validation
AtScene setting current validate scene.
func (*Validation) BindSafeData ¶
func (v *Validation) BindSafeData(ptr interface{}) error
BindSafeData binding safe data to an struct.
func (*Validation) BindStruct ¶ added in v1.2.1
func (v *Validation) BindStruct(ptr interface{}) error
BindStruct binding safe data to an struct.
func (*Validation) ConfigRules ¶ added in v1.1.2
func (v *Validation) ConfigRules(mp MS) *Validation
ConfigRules add multi rules by string map. alias of StringRules() Usage:
v.ConfigRules(map[string]string{ "name": "required|string|min:12", "age": "required|int|min:12", })
func (*Validation) EqField ¶
func (v *Validation) EqField(val interface{}, dstField string) bool
EqField value should EQ the dst field value
func (*Validation) FilterFuncValue ¶
func (v *Validation) FilterFuncValue(name string) reflect.Value
FilterFuncValue get filter by name
func (*Validation) FilterRule ¶
func (v *Validation) FilterRule(field string, rule string) *FilterRule
FilterRule add filter rule. Usage:
v.FilterRule("name", "trim|lower") v.FilterRule("age", "int")
func (*Validation) FilterRules ¶
func (v *Validation) FilterRules(rules map[string]string) *Validation
FilterRules add multi filter rules.
func (*Validation) Filtered ¶
func (v *Validation) Filtered(key string) interface{}
Filtered get filtered value by key
func (*Validation) FilteredData ¶
func (v *Validation) FilteredData() M
FilteredData return filtered data.
func (*Validation) GetDefValue ¶ added in v1.2.0
func (v *Validation) GetDefValue(field string) (interface{}, bool)
GetDefValue get default value of the field
func (*Validation) GetSafe ¶ added in v1.1.3
func (v *Validation) GetSafe(key string) interface{}
GetSafe get safe value by key
func (*Validation) GetWithDefault ¶ added in v1.2.1
func (v *Validation) GetWithDefault(key string) (val interface{}, exist, isDefault bool)
GetWithDefault get field value by key. On not found, if has default value, will return default-value.
func (*Validation) GtField ¶
func (v *Validation) GtField(val interface{}, dstField string) bool
GtField value should GT the dst field value
func (*Validation) GteField ¶
func (v *Validation) GteField(val interface{}, dstField string) bool
GteField value should GTE the dst field value
func (*Validation) HasValidator ¶
func (v *Validation) HasValidator(name string) bool
HasValidator check
func (*Validation) InMimeTypes ¶
func (v *Validation) InMimeTypes(fd *FormData, field, mimeType string, moreTypes ...string) bool
InMimeTypes check field is uploaded file and mime type is in the mimeTypes. Usage:
v.AddRule("video", "mimeTypes", "video/avi", "video/mpeg", "video/quicktime")
func (*Validation) InScene ¶
func (v *Validation) InScene(scene string) *Validation
InScene alias of the AtScene()
func (*Validation) IsFormFile ¶ added in v1.2.1
func (v *Validation) IsFormFile(fd *FormData, field string) (ok bool)
IsFormFile check field is uploaded file
func (*Validation) IsFormImage ¶ added in v1.2.1
func (v *Validation) IsFormImage(fd *FormData, field string, exts ...string) (ok bool)
IsFormImage check field is uploaded image file. Usage:
v.AddRule("avatar", "image") v.AddRule("avatar", "image", "jpg", "png", "gif") // set ext limit
func (*Validation) LtField ¶
func (v *Validation) LtField(val interface{}, dstField string) bool
LtField value should LT the dst field value
func (*Validation) LteField ¶
func (v *Validation) LteField(val interface{}, dstField string) bool
LteField value should LTE the dst field value(for int, string)
func (*Validation) NeField ¶
func (v *Validation) NeField(val interface{}, dstField string) bool
NeField value should not equal the dst field value
func (*Validation) Raw ¶
func (v *Validation) Raw(key string) (interface{}, bool)
Raw value get by key
func (*Validation) Required ¶
func (v *Validation) Required(field string, val interface{}) bool
Required field val check
func (*Validation) RequiredIf ¶ added in v1.1.4
func (v *Validation) RequiredIf(field string, val interface{}, kvs ...string) bool
RequiredIf field under validation must be present and not empty if the anotherField field is equal to any value.
func (*Validation) RequiredUnless ¶ added in v1.1.4
func (v *Validation) RequiredUnless(_ string, val interface{}, kvs ...string) bool
RequiredUnless field under validation must be present and not empty unless the anotherField field is equal to any value.
func (*Validation) RequiredWith ¶ added in v1.1.4
func (v *Validation) RequiredWith(_ string, val interface{}, kvs ...string) bool
RequiredWith field under validation must be present and not empty only if any of the other specified fields are present.
func (*Validation) RequiredWithAll ¶ added in v1.1.4
func (v *Validation) RequiredWithAll(_ string, val interface{}, kvs ...string) bool
RequiredWithAll field under validation must be present and not empty only if all of the other specified fields are present.
func (*Validation) RequiredWithout ¶ added in v1.1.4
func (v *Validation) RequiredWithout(_ string, val interface{}, kvs ...string) bool
RequiredWithout field under validation must be present and not empty only when any of the other specified fields are not present.
func (*Validation) RequiredWithoutAll ¶ added in v1.1.4
func (v *Validation) RequiredWithoutAll(_ string, val interface{}, kvs ...string) bool
RequiredWithoutAll field under validation must be present and not empty only when any of the other specified fields are not present.
func (*Validation) ResetResult ¶
func (v *Validation) ResetResult()
ResetResult reset the validate result.
func (*Validation) Safe ¶
func (v *Validation) Safe(key string) (val interface{}, ok bool)
Safe get safe value by key
func (*Validation) SafeData ¶
func (v *Validation) SafeData() M
SafeData get all validated safe data
func (*Validation) SafeVal ¶
func (v *Validation) SafeVal(key string) interface{}
SafeVal get safe value by key
func (*Validation) Scene ¶
func (v *Validation) Scene() string
Scene name get for current validation
func (*Validation) SceneFields ¶
func (v *Validation) SceneFields() []string
SceneFields field names get
func (*Validation) Set ¶
func (v *Validation) Set(field string, val interface{}) error
Set value by key
func (*Validation) SetDefValue ¶ added in v1.2.0
func (v *Validation) SetDefValue(field string, val interface{})
SetDefValue set an default value of given field
func (*Validation) SetScene ¶
func (v *Validation) SetScene(scene ...string) *Validation
SetScene alias of the AtScene()
func (*Validation) StringRule ¶
func (v *Validation) StringRule(field, rule string, filterRule ...string) *Validation
StringRule add field rules by string Usage:
v.StringRule("name", "required|string|minLen:6") // will try convert to int before apply validate. v.StringRule("age", "required|int|min:12", "toInt")
func (*Validation) StringRules ¶
func (v *Validation) StringRules(mp MS) *Validation
StringRules add multi rules by string map. Usage:
v.StringRules(map[string]string{ "name": "required|string|min_len:12", "age": "required|int|min:12", })
func (*Validation) Validate ¶
func (v *Validation) Validate(scene ...string) bool
Validate processing
func (*Validation) ValidateData ¶ added in v1.0.2
func (v *Validation) ValidateData(data DataFace) bool
ValidateData validate given data-source
func (*Validation) Validators ¶
func (v *Validation) Validators(withGlobal bool) map[string]int8
Validators get all validator names
func (*Validation) WithError ¶
func (v *Validation) WithError(err error) *Validation
WithError add error of the validation
func (*Validation) WithMessages ¶
func (v *Validation) WithMessages(m map[string]string) *Validation
WithMessages settings. you can custom validator error messages. Usage:
// key is "validator" or "field.validator" v.WithMessages(map[string]string{ "require": "oh! {field} is required", "range": "oh! {field} must be in the range %d - %d", })
func (*Validation) WithScenarios ¶
func (v *Validation) WithScenarios(scenes SValues) *Validation
WithScenarios is alias of the WithScenes()
func (*Validation) WithScenes ¶
func (v *Validation) WithScenes(scenes map[string][]string) *Validation
WithScenes set scene config. Usage:
v.WithScenes(SValues{ "create": []string{"name", "email"}, "update": []string{"name"}, }) ok := v.AtScene("create").Validate()
func (*Validation) WithTranslates ¶
func (v *Validation) WithTranslates(m map[string]string) *Validation
WithTranslates settings.you can custom field translates. Usage:
v.WithTranslates(map[string]string{ "name": "User Name", "pwd": "Password", })