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/v2
Index ¶
- Constants
- Variables
- func AddBuiltinMessages(mp map[string]string)
- func AddCustomType(fn CustomTypeFunc, types ...any)
- func AddFilter(name string, filterFunc any)
- func AddFilters(m map[string]any)
- func AddGlobalMessages(mp map[string]string)
- func AddValidator(name string, checkFunc any)
- func AddValidators(m map[string]any)
- 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, minVal, maxVal any) bool
- func BuiltinMessages() map[string]string
- func ByteLength(str string, minLen int, maxLen ...int) bool
- func CalcLength(val any) int
- func CallByValue(fv reflect.Value, args ...any) []reflect.Value
- func Config(fn func(opt *GlobalOption))
- func Contains(s, sub any) bool
- func CopyGlobalMessages() map[string]string
- func DateFormat(s string, layout string) bool
- func EndsWith(s, sub string) bool
- func Enum(val, enum any) bool
- func Gt(val, minVal any) bool
- func Gte(val, minVal any) bool
- func HasLowerCase(s string) bool
- func HasURLSchema(s string) bool
- func HasUpperCase(s string) bool
- func HasWhitespace(s string) bool
- func IntEqual(val any, wantVal int64) bool
- func IsASCII(s string) bool
- func IsActiveURL(s string) bool
- func IsAlpha(s string) bool
- func IsAlphaDash(s string) bool
- func IsAlphaNum(s string) bool
- func IsArray(val any, strict ...bool) (ok bool)
- func IsBase64(s string) bool
- func IsBool(val any) 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, layouts ...string) bool
- func IsDirPath(path string) bool
- func IsEmail(s string) bool
- func IsEmpty(val any) bool
- func IsEqual(val, wantVal any) bool
- func IsFilePath(path string) bool
- func IsFloat(val any) 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 any, minAndMax ...int64) (ok bool)
- func IsIntString(s string) bool
- func IsInts(val any) bool
- func IsJSON(s string) bool
- func IsLatitude(s string) bool
- func IsLongitude(s string) bool
- func IsMAC(s string) bool
- func IsMap(val any) (ok bool)
- func IsMultiByte(s string) bool
- func IsNilObj(val any) bool
- func IsNumber(v any) bool
- func IsNumeric(v any) bool
- func IsPrintableASCII(s string) bool
- func IsRGBColor(s string) bool
- func IsSlice(val any) (ok bool)
- func IsString(val any, minAndMaxLen ...int) (ok bool)
- func IsStringNumber(s string) bool
- func IsStrings(val any) (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 any) bool
- func IsUnixPath(s string) bool
- func IsWinPath(s string) bool
- func IsZero(v reflect.Value) bool
- func Length(val any, wantLen int) bool
- func Lt(val, maxVal any) bool
- func Lte(val, maxVal any) bool
- func Max(val, maxVal any) bool
- func MaxLength(val any, maxLen int) bool
- func Min(val, minVal any) bool
- func MinLength(val any, minLen int) bool
- func NotContains(s, sub any) bool
- func NotEqual(val, wantVal any) bool
- func NotIn(val, enum any) bool
- func PathExists(path string) bool
- func Regexp(str string, pattern string) bool
- func ResetCustomTypes()
- func ResetOption()
- func ResetTypeCache()
- func RuneLength(val any, minLen int, maxLen ...int) bool
- func SetBuiltinMessages(mp map[string]string)
- func StartsWith(s, sub string) bool
- func StringContains(s, sub string) bool
- func StringLength(val any, minLen int, maxLen ...int) bool
- func Val(val any, rule string) error
- func ValidatorName(name string) string
- func Validators() map[string]int8
- func ValueIsEmpty(v reflect.Value) bool
- func Var(val any, rule string) error
- type ConfigValidationFace
- type CustomMessagesFace
- type CustomTypeFunc
- 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) ErrOrNil() error
- 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) JSON() []byte
- func (es Errors) One() string
- func (es Errors) OneError() error
- func (es Errors) Random() string
- func (es Errors) String() string
- type Factory
- type FieldTranslatorFace
- type FilterRule
- type FormData
- func (d *FormData) Add(key, value string)
- func (d *FormData) AddFile(key string, files ...*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) FilesMimeType(field string) (mimes []string)
- func (d *FormData) Float(key string) float64
- func (d *FormData) Get(key string) (any, bool)
- func (d *FormData) GetFile(key string) *multipart.FileHeader
- func (d *FormData) GetFiles(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 any) (newVal any, err error)
- func (d *FormData) Src() any
- func (d *FormData) String(key string) string
- func (d *FormData) Strings(key string) []string
- func (d *FormData) TryGet(key string) (val any, exist, zero bool)
- 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 any) error
- func (d *MapData) Create(err ...error) *Validation
- func (d *MapData) Get(field string) (any, bool)
- func (d *MapData) Set(field string, val any) (any, error)
- func (d *MapData) Src() any
- func (d *MapData) TryGet(field string) (val any, exist, zero bool)
- 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 any) *Rule
- func (r *Rule) SetFilterFunc(fn func(val any) (any, 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) (val any, exist bool)
- func (d *StructData) HasField(field string) bool
- func (d *StructData) Set(field string, val any) (newVal any, err error)
- func (d *StructData) Src() any
- func (d *StructData) TryGet(field string) (val any, exist, zero bool)
- 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) AddLabelMap(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) FieldName(field string) string
- func (t *Translator) HasField(field string) bool
- func (t *Translator) HasLabel(field string) bool
- func (t *Translator) HasMessage(key string) bool
- func (t *Translator) LabelMap() map[string]string
- func (t *Translator) LabelName(field string) string
- func (t *Translator) LookupLabel(field string) (string, bool)
- func (t *Translator) Message(validator, field string, args ...any) (msg string)
- func (t *Translator) Reset()
- type UnmarshalFunc
- type Validation
- func JSON(s string, scene ...string) *Validation
- func Map(m map[string]any, scene ...string) *Validation
- func New(data any, scene ...string) *Validation
- func NewEmpty(scene ...string) *Validation
- func NewValidation(data DataFace, scene ...string) *Validation
- func Request(r *http.Request) *Validation
- func Struct(s any, scene ...string) *Validation
- func (v *Validation) AddError(field, validator, msg string)
- func (v *Validation) AddErrorf(field, msgFormat string, args ...any)
- func (v *Validation) AddFilter(name string, filterFunc any)
- func (v *Validation) AddFilters(m map[string]any)
- func (v *Validation) AddMessages(m map[string]string)
- func (v *Validation) AddRule(fields, validator string, args ...any) *Rule
- func (v *Validation) AddTranslates(m map[string]string)
- func (v *Validation) AddValidator(name string, checkFunc any) *Validation
- func (v *Validation) AddValidators(m map[string]any) *Validation
- func (v *Validation) AppendRule(rule *Rule) *Rule
- func (v *Validation) AppendRules(rules ...*Rule) *Validation
- func (v *Validation) AtScene(scene string) *Validation
- func (v *Validation) BindSafeData(ptr any) error
- func (v *Validation) BindStruct(ptr any) error
- func (v *Validation) ConfigRules(mp MS) *Validation
- func (v *Validation) EqField(val any, 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) any
- func (v *Validation) FilteredData() M
- func (v *Validation) Filtering() bool
- func (v *Validation) Get(key string) (val any, exist bool)
- func (v *Validation) GetDefValue(field string) (any, bool)
- func (v *Validation) GetSafe(key string) any
- func (v *Validation) GetWithDefault(key string) (val any, exist, isDefault bool)
- func (v *Validation) GtField(val any, dstField string) bool
- func (v *Validation) GteField(val any, 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 any, dstField string) bool
- func (v *Validation) LteField(val any, dstField string) bool
- func (v *Validation) NeField(val any, dstField string) bool
- func (v *Validation) Raw(key string) (any, bool)
- func (v *Validation) RawVal(key string) any
- func (v *Validation) Release()
- func (v *Validation) Required(field string, val any) bool
- func (v *Validation) RequiredIf(sourceField string, val any, kvs ...string) bool
- func (v *Validation) RequiredUnless(sourceField string, val any, kvs ...string) bool
- func (v *Validation) RequiredWith(sourceField string, val any, fields ...string) bool
- func (v *Validation) RequiredWithAll(sourceField string, val any, fields ...string) bool
- func (v *Validation) RequiredWithout(sourceField string, val any, fields ...string) bool
- func (v *Validation) RequiredWithoutAll(sourceField string, val any, fields ...string) bool
- func (v *Validation) Reset()
- func (v *Validation) ResetResult()
- func (v *Validation) RuleOneOf(val any, rules any) bool
- func (v *Validation) Safe(key string) (val any, ok bool)
- func (v *Validation) SafeData() M
- func (v *Validation) SafeVal(key string) any
- func (v *Validation) Sanitize() bool
- func (v *Validation) Scene() string
- func (v *Validation) SceneFields() []string
- func (v *Validation) Set(field string, val any) error
- func (v *Validation) SetDefValue(field string, val any)
- func (v *Validation) SetScene(scene ...string) *Validation
- func (v *Validation) StringMessage(field, message string) *Validation
- func (v *Validation) StringMessages(mp MS) *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) ValidateE(scene ...string) Errors
- func (v *Validation) ValidateErr(scene ...string) error
- 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) WithSelf(fn func(v *Validation)) *Validation
- func (v *Validation) WithTrans(trans *Translator) *Validation
- func (v *Validation) WithTranslates(m map[string]string) *Validation
Examples ¶
Constants ¶
const ( RuleRequired = "required" RuleOptional = "optional" RuleDefault = "default" RuleRegexp = "regexp" // RuleSafe means skip validate this field RuleSafe = "safe" RuleSafe1 = "-" )
some commonly validation rule names.
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 requires scheme + a structured host (domain.tld or IPv4), with an // optional port and path/query/fragment. The host structure is what rejects // the over-permissive cases of the old `[\w./#=?&-_%]+` blob (#138): a missing // TLD ("https://www"), invalid host chars ("https://not%23"), or an underscore // in the host ("https://www.googl_?e.com/..."). FullURL = `` /* 145-byte string literal not displayed */ 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 ( ErrUnaddressableField = errors.New("cannot set value as it was not passed-by-reference") 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
var ActiveURLTimeout = 5 * time.Second
ActiveURLTimeout is the per-request timeout used by IsActiveURL when probing a URL for reachability. Adjust it to tune how long to wait for the remote server before treating the URL as inactive.
var (
// DefaultFieldName for value validate.
DefaultFieldName = "input"
)
var ErrConvertFail = errors.New("convert value is failure")
ErrConvertFail error
NilValue TODO a reflect nil value, use for instead of nilRVal
Functions ¶
func AddBuiltinMessages ¶
AddBuiltinMessages alias of the AddGlobalMessages()
func AddCustomType ¶
func AddCustomType(fn CustomTypeFunc, types ...any)
AddCustomType 为给定样例类型注册底层值提取器(命名与 AddValidator 一致)。
按传入样例的精确 reflect.Type 存储,不自动解指针:传 sql.NullString{} 只 匹配该值类型;若要同时匹配指针,需另外传入 &sql.NullString{} 样例。
func AddGlobalMessages ¶
AddGlobalMessages add global builtin messages
func AddValidator ¶
AddValidator to the pkg. checkFunc must return a bool
Usage:
v.AddValidator("myFunc", func(val any) bool {
// do validate val ...
return true
})
func AddValidators ¶
AddValidators to the global validators map
func BeforeOrEqualDate ¶
BeforeOrEqualDate check
func Between ¶
Between value in the given range (inclusive). only check for: int(X), uint(X), float(X), string.
func BuiltinMessages ¶
BuiltinMessages get builtin messages
func ByteLength ¶
ByteLength check string's length
func CallByValue ¶
CallByValue call func by reflect.Value
func Contains ¶
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 CopyGlobalMessages ¶
CopyGlobalMessages copy get builtin messages
func Gte ¶
Gte check value greater or equal dst value only check for: int(X), uint(X), float(X), string.
func IsActiveURL ¶
IsActiveURL reports whether s is a reachable/active URL.
It first does a cheap structural check via IsFullURL (must have scheme+host); an invalid full URL returns false WITHOUT any network access. Otherwise it issues a real HTTP request: a HEAD first, falling back to GET when the server answers 405 (Method Not Allowed). A final status code < 400 (2xx/3xx, after following the default redirects) is considered active and returns true; any transport error or status code >= 400 returns false.
NOTE: this performs a real, network-dependent HTTP request, so it may be slow. Tune the timeout via the package-level ActiveURLTimeout. When validating untrusted input, be aware of the SSRF risk (an attacker-controlled URL causes your server to make outbound requests) and gate it accordingly.
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 ¶
IsEqual check two value is equals. Don't compare func, struct
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 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 ¶
IsStringNumber is string number. should >= 0
func IsURL ¶
IsURL string. This is a loose URI-reference check (relative refs, paths and bare hosts are accepted); for a strict absolute URL use IsFullURL.
func IsZero ¶
IsZero reports whether v is the zero value for its type. It panics if the argument is invalid.
NOTICE: this 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), string.
func NotContains ¶
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 PathExists ¶
PathExists reports whether the named file or directory exists.
func ResetCustomTypes ¶
func ResetCustomTypes()
ResetCustomTypes 清空所有已注册的自定义类型提取器并复位门控(测试/清理用, 参照 ResetTypeCache)。通过 Range+Delete 实现以保持并发安全。
func ResetTypeCache ¶
func ResetTypeCache()
ResetTypeCache clears the whole type metadata cache. Intended for tests and special cases where forcing a rebuild is desired. Implemented via Range+Delete (instead of swapping the sync.Map pointer) to stay concurrency-safe.
func RuneLength ¶
RuneLength check string's length (including multibyte strings)
func SetBuiltinMessages ¶
SetBuiltinMessages override set builtin messages
func StartsWith ¶
StartsWith check string is starts with sub-string
func StringContains ¶
StringContains check string is containing sub-string
func StringLength ¶
StringLength check string's length (including multibyte strings)
func Val ¶
Val quick validating the value by given rule. returns error on fail, return nil on check ok.
Usage:
validate.Val("xyz@mail.com", "required|email")
refer the Validation.StringRule() for parse rule string.
func ValueIsEmpty ¶
ValueIsEmpty check. alias of reflects.IsEmpty()
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! Username is required",
}
}
type CustomTypeFunc ¶
CustomTypeFunc 从自定义类型字段提取 validate 实际要校验的底层值。
返回 nil 表示"视为空/未设置"(required 失败)。提取后的值天然走现有 valueCompare / IsEmpty / Length / string 校验路径。对标 go-playground/validator 的 RegisterCustomTypeFunc。
type DataFace ¶
type DataFace interface {
Type() uint8
Src() any
Get(key string) (val any, exist bool)
// TryGet value by key.
// if source data is struct, will return zero check
TryGet(key string) (val any, exist, zero bool)
Set(field string, val any) (any, error)
// Create 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": {
"required": "error message",
"min_len": "error message1"
}
}
type Factory ¶
type Factory struct {
// contains filtered or unexported fields
}
Factory is an opt-in pooled Validation factory. It reuses *Validation instances from a sync.Pool across many same-type validations, amortizing the per-instance construction cost (newEmpty + translator + rule instantiate).
It is NON-default: validate.New / validate.Struct / validate.Map and their lifecycle are unchanged. Only callers who explicitly opt in via a Factory get pooling, and they MUST call v.Release() to return the instance to the pool.
Usage:
f := validate.NewFactory()
for _, u := range users {
v := f.Struct(&u) // pooled instance + cached type meta
v.Validate()
// ... use v.Errors / v.SafeData() ...
v.Release() // fully Reset + return to pool
}
A Validation obtained from a Factory behaves identically to validate.Struct / validate.Map (same rules, same result). Do NOT keep using a *Validation after Release(): it may be handed to another caller.
func NewFactory ¶
func NewFactory() *Factory
NewFactory creates a Factory with its own private pool. Each pooled instance starts life as a newEmpty()-level blank Validation (same initial state as the default path's NewValidation).
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": "Username",
}
}
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
}
FormData obtained from the request body or url query parameters or user custom setting.
func FromURLValues ¶
FromURLValues build data instance.
Bracket-style nested keys are normalized to dot paths so nested form fields can be validated and bound, eg "address[street]" -> "address.street" (#324).
func (*FormData) Add ¶
Add adds the value to key. It appends to any existing values associated with a key.
func (*FormData) AddFile ¶
func (d *FormData) AddFile(key string, files ...*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 a key (if any). If there is no file associated with a 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) FilesMimeType ¶
FilesMimeType get all File Mime Type names by field.
func (*FormData) GetFile ¶
func (d *FormData) GetFile(key string) *multipart.FileHeader
GetFile returns the multipart form file associated with a key, if any, as a *multipart.FileHeader. If there is no file associated with a key, it returns nil. If you just want the body of the file, use GetFileBytes.
func (*FormData) GetFiles ¶
func (d *FormData) GetFiles(key string) []*multipart.FileHeader
GetFiles returns the multipart form files associated with a key, if any, as a []*multipart.FileHeader.
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 creates from data
type GlobalOption ¶
type GlobalOption struct {
// FilterTag name in the struct tags.
//
// default: filter
FilterTag string
// ValidateTag in the struct tags.
//
// default: validate
ValidateTag string
// FieldTag the output field name in the struct tags.
// it as placeholder on error message.
//
// default: json
FieldTag string
// LabelTag the display name in the struct tags.
// use for define field translate name on error.
//
// default: label
LabelTag string
// MessageTag define error message for the field.
//
// default: message
MessageTag string
// DefaultTag define default value for the field.
//
// tag: default TODO
DefaultTag string
// StopOnError If true: An error occurs, it will cease to continue to verify. default is True.
StopOnError bool
// SkipOnEmpty Skip check on field not exist or value is empty. default is True.
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
// ErrShowValue Whether to append the original value that triggered the error
// to the error message. opt-in, default is false (keeps error messages
// byte-for-byte unchanged). When true, the failing value is appended in the
// form " (value: <val>)". see GitHub issue #184.
ErrShowValue bool
// CheckZero whether to validate the zero value. (intX,uintX: 0, string: "")
//
// Deprecated: this flag is a no-op — it was declared but never wired into the
// validation logic. To validate empty/zero values instead of skipping them,
// use per-rule Rule.SetSkipEmpty(false), set SkipOnEmpty=false on the
// Validation/global option, or mark the field as required. It will be removed
// in a future release.
CheckZero bool
// ErrKeyFmt config. TODO
//
// allow:
// - 0 use struct field name as key. (for compatible)
// - 1 use FieldTag defined name as key.
ErrKeyFmt int8
// CheckSubOnParentMarked controls sub-struct (struct / *struct / slice-of-struct /
// map-of-struct) cascade validation.
//
// 默认 true: 仅当父字段带有 `validate` tag(值可为空, 如 `validate:""`)时才级联验证
// 其子结构体; 完全没有 `validate` tag 的字段不会下探。设为 false 则无条件级联(v1 行为)。
CheckSubOnParentMarked bool
// ValidatePrivateFields Whether to validate private fields or not, especially when inheriting other other structs.
//
// type foo struct {
// Field int `json:"field" validate:"required"`
// }
// type bar struct {
// foo // <-- validate this field
// Field2 int `json:"field2" validate:"required"`
// }
//
// default: false
ValidatePrivateFields bool
// RestoreRequestBody Whether to restore the request body after reading it.
// default: false
RestoreRequestBody bool
}
GlobalOption settings for validate
type MapData ¶
type MapData struct {
// Map the source map data
Map map[string]any
// 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 creates from data
type NilObject ¶
NilObject represent nil value for calling functions and should be reflected at custom filters as nil variable.
Alias of reflectx.NilObject: keeps the public type identity so that any val.(NilObject) assertion and IsNilObj keep working unchanged after the type was moved into internal/reflectx.
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 {
// FilterTag name in the struct tags.
//
// see GlobalOption.FilterTag
FilterTag string
// ValidateTag name in the struct tags.
//
// see GlobalOption.ValidateTag
ValidateTag string
// contains filtered or unexported fields
}
StructData definition.
more struct tags define please see GlobalOption
func (*StructData) Create ¶
func (d *StructData) Create(err ...error) *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) (val any, exist bool)
Get value by field name. support get sub-value by path.
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 any) (newVal any, err error)
Set value by field name.
Notice: `StructData.src` the incoming struct must be a pointer to set the value
func (*StructData) TryGet ¶
func (d *StructData) TryGet(field string) (val any, exist, zero bool)
TryGet value by field name. support get sub-value by path.
func (*StructData) Validation ¶
func (d *StructData) Validation(err ...error) *Validation
Validation creates 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 output name data. If you want to display in the field with the original field is not the same
func (*Translator) AddLabelMap ¶
func (t *Translator) AddLabelMap(fieldMap map[string]string)
AddLabelMap config field translate data map. 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 ¶
func (t *Translator) AddMessages(data map[string]string)
AddMessages data to translator
func (*Translator) FieldName ¶
func (t *Translator) FieldName(field string) string
FieldName get in the t.fieldMap
func (*Translator) HasField ¶
func (t *Translator) HasField(field string) bool
HasField name in the t.fieldMap.
func (*Translator) HasLabel ¶
func (t *Translator) HasLabel(field string) bool
HasLabel name in the t.labelMap
func (*Translator) HasMessage ¶
func (t *Translator) HasMessage(key string) bool
HasMessage key in the t.messages, fallback to global builtinMessages.
func (*Translator) LabelName ¶
func (t *Translator) LabelName(field string) string
LabelName get label name from the t.labelMap, fallback get output name from t.fieldMap
func (*Translator) LookupLabel ¶
func (t *Translator) LookupLabel(field string) (string, bool)
LookupLabel get label name from the t.labelMap, fallback get output name from t.fieldMap. if not found, return "", false
type Validation ¶
type Validation struct {
// Errors for 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
// ErrShowValue Whether to append the failing value to the error message.
// opt-in, copied from gOpt. see GitHub issue #184.
ErrShowValue 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 any, scene ...string) *Validation
New create a Validation instance
data type support:
- DataFace
- M/map[string]any
- SValues/url.Values/map[string][]string
- struct ptr
func NewEmpty ¶
func NewEmpty(scene ...string) *Validation
NewEmpty new validation instance, but not with data.
func NewValidation ¶
func NewValidation(data DataFace, scene ...string) *Validation
NewValidation new validation instance
func Struct ¶
func Struct(s any, scene ...string) *Validation
Struct validation create
Example ¶
// UserForm struct
type UserForm struct {
Name string `validate:"required|minLen:7" message:"required:{field} is required" label:"User Name"`
Email string `validate:"email" message:"email:input must be a EMAIL address"`
CreateAt int `validate:"email"`
Safe int `validate:"-"`
UpdateAt time.Time `validate:"required"`
Code string `validate:"customValidator|default:abc"`
Status int `validate:"required|gtField:Extra.0.Status1"`
Extra []ExtraInfo `validate:"required"`
protected string //nolint:unused
}
u := &UserForm{
Name: "inhere",
}
v := Struct(u)
ok := v.Validate()
fmt.Println(ok)
dump.P(v.Errors, u)
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 ...any)
AddErrorf add a formatted error message
func (*Validation) AddFilter ¶
func (v *Validation) AddFilter(name string, filterFunc any)
AddFilter to the Validation.
func (*Validation) AddFilters ¶
func (v *Validation) AddFilters(m map[string]any)
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 ...any) *Rule
AddRule for current validation
Usage:
v.AddRule("name", "required")
v.AddRule("name", "min_len", "2")
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 any) *Validation
AddValidator to the Validation instance. checkFunc must return a bool.
Usage:
v.AddValidator("myFunc", func(data validate.DataFace, val any) bool {
// do validate val ...
return true
})
func (*Validation) AddValidators ¶
func (v *Validation) AddValidators(m map[string]any) *Validation
AddValidators to the Validation instance.
func (*Validation) AppendRule ¶
func (v *Validation) AppendRule(rule *Rule) *Rule
AppendRule instance
func (*Validation) AppendRules ¶
func (v *Validation) AppendRules(rules ...*Rule) *Validation
AppendRules instances at once
func (*Validation) AtScene ¶
func (v *Validation) AtScene(scene string) *Validation
AtScene setting current validate scene.
func (*Validation) BindSafeData ¶
func (v *Validation) BindSafeData(ptr any) error
BindSafeData binding safe data to an struct.
func (*Validation) BindStruct ¶
func (v *Validation) BindStruct(ptr any) error
BindStruct binding safe data to a struct. alias of BindSafeData
func (*Validation) ConfigRules ¶
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 any, 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) any
Filtered get filtered value by key
func (*Validation) FilteredData ¶
func (v *Validation) FilteredData() M
FilteredData return filtered data.
func (*Validation) Get ¶
func (v *Validation) Get(key string) (val any, exist bool)
Get value by key.
func (*Validation) GetDefValue ¶
func (v *Validation) GetDefValue(field string) (any, bool)
GetDefValue get default value of the field
func (*Validation) GetSafe ¶
func (v *Validation) GetSafe(key string) any
GetSafe get safe value by key
func (*Validation) GetWithDefault ¶
func (v *Validation) GetWithDefault(key string) (val any, exist, isDefault bool)
GetWithDefault get field value by key.
On not found, if it has default value, will return default-value.
func (*Validation) GtField ¶
func (v *Validation) GtField(val any, dstField string) bool
GtField value should GT the dst field value
func (*Validation) GteField ¶
func (v *Validation) GteField(val any, 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 mimetype is in the mimeTypes. validator: inMimeTypes
Usage:
v.AddRule("video", "mimeTypes", "video/avi", "video/mpeg", "video/quicktime")
v.AddRule("videos.*", "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 ¶
func (v *Validation) IsFormFile(fd *FormData, field string) (ok bool)
IsFormFile check field is uploaded file. validator: isFile
func (*Validation) IsFormImage ¶
func (v *Validation) IsFormImage(fd *FormData, field string, exts ...string) (ok bool)
IsFormImage check field is uploaded image file. validator: isImage
Usage:
v.AddRule("avatar", "image")
v.AddRule("avatar", "image", "jpg", "png", "gif") // set ext limit
v.AddRule("images.*", "image")
v.AddRule("images.*", "image", "jpg", "png", "gif") // set ext limit
func (*Validation) LtField ¶
func (v *Validation) LtField(val any, dstField string) bool
LtField value should LT the dst field value
func (*Validation) LteField ¶
func (v *Validation) LteField(val any, dstField string) bool
LteField value should LTE the dst field value(for int, string)
func (*Validation) NeField ¶
func (v *Validation) NeField(val any, dstField string) bool
NeField value should not equal the dst field value
func (*Validation) Release ¶
func (v *Validation) Release()
Release fully resets the Validation and returns it to its owning Factory pool. It is a no-op for instances NOT obtained from a Factory (v.pool == nil), so it is always safe to call. After Release() the instance must not be used again.
func (*Validation) Required ¶
func (v *Validation) Required(field string, val any) bool
Required field val check
func (*Validation) RequiredIf ¶
func (v *Validation) RequiredIf(sourceField string, val any, kvs ...string) bool
RequiredIf field under validation must be present and not empty, if the anotherField field is equal to any value.
Usage:
v.AddRule("password", "requiredIf", "username", "tom")
func (*Validation) RequiredUnless ¶
func (v *Validation) RequiredUnless(sourceField string, val any, kvs ...string) bool
RequiredUnless field under validation must be present and not empty unless the dstField field is equal to any value.
- kvs format: [dstField, dstVal1, dstVal2 ...]
func (*Validation) RequiredWith ¶
func (v *Validation) RequiredWith(sourceField string, val any, fields ...string) bool
RequiredWith field under validation must be present and not empty only if any of the other specified fields are present.
- fields format: [field1, field2 ...]
func (*Validation) RequiredWithAll ¶
func (v *Validation) RequiredWithAll(sourceField string, val any, fields ...string) bool
RequiredWithAll field under validation must be present and not empty only if all the other specified fields are present.
func (*Validation) RequiredWithout ¶
func (v *Validation) RequiredWithout(sourceField string, val any, fields ...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 ¶
func (v *Validation) RequiredWithoutAll(sourceField string, val any, fields ...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) Reset ¶
func (v *Validation) Reset()
Reset the Validation instance.
Will resets:
- validate result
- validate rules
- validate filterRules
- custom validators TODO
func (*Validation) ResetResult ¶
func (v *Validation) ResetResult()
ResetResult reset the validate result.
func (*Validation) RuleOneOf ¶
func (v *Validation) RuleOneOf(val any, rules any) bool
RuleOneOf 规则级"逻辑或"(#292): val 满足列出的任一子校验器即通过, 全部不满足才失败。
- rules 为子校验器名列表 (来自 rule.go 的 parseArgString, 即 args[0] 的 []string)。
- 子项名支持别名 (ip->isIP, cidr->isCIDR), 经 ValidatorName 解析后取 funcMeta。
- phase1 仅支持无参子校验器, 故在原 val 上以 addNum=1 直接调用, 不传 field/args。
- 未知子校验器名 → 直接 panic, 与现有"未知 validator"行为一致, 提前暴露拼写错误。
func (*Validation) Safe ¶
func (v *Validation) Safe(key string) (val any, 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) any
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) SetDefValue ¶
func (v *Validation) SetDefValue(field string, val any)
SetDefValue set a default value of given field
func (*Validation) SetScene ¶
func (v *Validation) SetScene(scene ...string) *Validation
SetScene alias of the AtScene()
func (*Validation) StringMessage ¶
func (v *Validation) StringMessage(field, message string) *Validation
StringMessage set error messages for a field by a tag-style string. It mirrors the `message` struct tag format, the same way StringRule mirrors the rule tag. Chainable, returns *Validation.
Message string format:
- multiple, per-validator: split by "|", each segment is "validator:message". it is registered under the "field.validator" key.
- single, field-level: a segment without ":" is registered under the bare "field" key and acts as a fallback message for any failing validator of the field.
Usage:
// per-validator messages
v.StringMessage("name", "required:name is required|minLen:name is too short")
// field-level fallback message
v.StringMessage("name", "name is invalid")
func (*Validation) StringMessages ¶
func (v *Validation) StringMessages(mp MS) *Validation
StringMessages set error messages for multi fields by string map. It mirrors StringRules: map key is the field, value is the tag-style message spec.
Usage:
v.StringMessages(validate.MS{
"name": "required:name is required|minLen:name is too short",
"age": "age is invalid",
})
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 applying validation.
v.StringRule("age", "required|int|min:12", "toInt")
v.StringRule("email", "required|min_len:6", "trim|email|lower")
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 ¶
func (v *Validation) ValidateData(data DataFace) bool
ValidateData validate given data-source
func (*Validation) ValidateE ¶
func (v *Validation) ValidateE(scene ...string) Errors
ValidateE do validate processing and return Errors
NOTE: need use len() to check the return is empty or not.
func (*Validation) ValidateErr ¶
func (v *Validation) ValidateErr(scene ...string) error
ValidateErr do validate processing and return error
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) WithSelf ¶
func (v *Validation) WithSelf(fn func(v *Validation)) *Validation
WithSelf config the Validation instance. TODO rename to WithConfig
func (*Validation) WithTrans ¶
func (v *Validation) WithTrans(trans *Translator) *Validation
WithTrans with a custom translator
func (*Validation) WithTranslates ¶
func (v *Validation) WithTranslates(m map[string]string) *Validation
WithTranslates settings. you can be custom field translates.
Usage:
v.WithTranslates(map[string]string{
"name": "Username",
"pwd": "Password",
})
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
httpdemo
command
|
|
|
httpdemo2
command
|
|
|
internal
|
|
|
fieldval
Package fieldval holds the internal value carrier (FieldValue) that flows through the validating pipeline.
|
Package fieldval holds the internal value carrier (FieldValue) that flows through the validating pipeline. |
|
reflectx
Package reflectx holds pure reflection helpers extracted from the validate root package.
|
Package reflectx holds pure reflection helpers extracted from the validate root package. |
|
locales
|
|