README
¶
validation
fork form github.com/astaxie/beego/validation
validation is a form validation for a data validation and error collecting using Go.
Installation and tests
Install:
go get github.com/youpenglai/goutils/validation
Test:
go test github.com/youpenglai/goutils/validation
Example
Direct Use:
import (
"github.com/youpenglai/goutils/validation"
"log"
)
type User struct {
Name string
Age int
}
func main() {
u := User{"man", 40}
valid := validation.Validation{}
valid.Required(u.Name, "name")
valid.MaxSize(u.Name, 15, "nameMax")
valid.Range(u.Age, 0, 140, "age")
if valid.HasErrors() {
// validation does not pass
// print invalid message
for _, err := range valid.Errors {
log.Println(err.Key, err.Message)
}
}
// or use like this
if v := valid.Max(u.Age, 140, "ageMax"); !v.Ok {
log.Println(v.Error.Key, v.Error.Message)
}
}
Struct Tag Use:
import (
"github.com/astaxie/beego/validation"
)
// validation function follow with "valid" tag
// functions divide with ";"
// parameters in parentheses "()" and divide with ","
// Match function's pattern string must in "//"
type user struct {
Id int
Name string `valid:"Required;Match(/^(test)?\\w*@;com$/)"`
Age int `valid:"Required;Range(1, 140)"`
}
func main() {
valid := validation.Validation{}
// ignore empty field valid
// see CanSkipFuncs
// valid := validation.Validation{RequiredFirst:true}
u := user{Name: "test", Age: 40}
b, err := valid.Valid(u)
if err != nil {
// handle error
}
if !b {
// validation does not pass
// blabla...
}
}
Use custom function:
import (
"github.com/astaxie/beego/validation"
)
type user struct {
Id int
Name string `valid:"Required;IsMe"`
Age int `valid:"Required;Range(1, 140)"`
}
func IsMe(v *validation.Validation, obj interface{}, key string) {
name, ok:= obj.(string)
if !ok {
// wrong use case?
return
}
if name != "me" {
// valid false
v.SetError("Name", "is not me!")
}
}
func main() {
valid := validation.Validation{}
if err := validation.AddCustomFunc("IsMe", IsMe); err != nil {
// hadle error
}
u := user{Name: "test", Age: 40}
b, err := valid.Valid(u)
if err != nil {
// handle error
}
if !b {
// validation does not pass
// blabla...
}
}
Struct Tag Functions:
Required
Min(min int)
Max(max int)
Range(min, max int)
MinSize(min int)
MaxSize(max int)
Length(length int)
Alpha
Numeric
AlphaNumeric
Match(pattern string)
AlphaDash
Email
IP
Base64
Mobile
Tel
Phone
ZipCode
Documentation
¶
Overview ¶
Package validation for validations
import ( "github.com/astaxie/beego/validation" "log" ) type User struct { Name string Age int } func main() { u := User{"man", 40} valid := validation.Validation{} valid.Required(u.Name, "name") valid.MaxSize(u.Name, 15, "nameMax") valid.Range(u.Age, 0, 140, "age") if valid.HasErrors() { // validation does not pass // print invalid message for _, err := range valid.Errors { log.Println(err.Key, err.Message) } } // or use like this if v := valid.Max(u.Age, 140, "ageMax"); !v.Ok { log.Println(v.Error.Key, v.Error.Message) } }
more info: http://beego.me/docs/mvc/controller/validation.md
Index ¶
- Constants
- Variables
- func AddCustomFunc(name string, f CustomFunc) error
- func SetDefaultMessage(msg map[string]string)
- type Alpha
- type AlphaDash
- type AlphaNumeric
- type Base64
- type CustomFunc
- type Email
- type Error
- type Funcs
- type IP
- type Length
- type Match
- type Max
- type MaxSize
- type Min
- type MinSize
- type Mobile
- type NoMatch
- type Numeric
- type Phone
- type Range
- type Required
- type Result
- type Tel
- type ValidFormer
- type ValidFunc
- type Validation
- func (v *Validation) AddError(key, message string)
- func (v *Validation) Alpha(obj interface{}, key string) *Result
- func (v *Validation) AlphaDash(obj interface{}, key string) *Result
- func (v *Validation) AlphaNumeric(obj interface{}, key string) *Result
- func (v *Validation) Base64(obj interface{}, key string) *Result
- func (v *Validation) CanSkipAlso(skipFunc string)
- func (v *Validation) Check(obj interface{}, checks ...Validator) *Result
- func (v *Validation) Clear()
- func (v *Validation) Email(obj interface{}, key string) *Result
- func (v *Validation) Error(message string, args ...interface{}) *Result
- func (v *Validation) ErrorMap() map[string][]*Error
- func (v *Validation) HasErrors() bool
- func (v *Validation) IP(obj interface{}, key string) *Result
- func (v *Validation) Length(obj interface{}, n int, key string) *Result
- func (v *Validation) Match(obj interface{}, regex *regexp.Regexp, key string) *Result
- func (v *Validation) Max(obj interface{}, max int, key string) *Result
- func (v *Validation) MaxSize(obj interface{}, max int, key string) *Result
- func (v *Validation) Min(obj interface{}, min int, key string) *Result
- func (v *Validation) MinSize(obj interface{}, min int, key string) *Result
- func (v *Validation) Mobile(obj interface{}, key string) *Result
- func (v *Validation) NoMatch(obj interface{}, regex *regexp.Regexp, key string) *Result
- func (v *Validation) Numeric(obj interface{}, key string) *Result
- func (v *Validation) Phone(obj interface{}, key string) *Result
- func (v *Validation) Range(obj interface{}, min, max int, key string) *Result
- func (v *Validation) RecursiveValid(objc interface{}) (bool, error)
- func (v *Validation) Required(obj interface{}, key string) *Result
- func (v *Validation) SetError(fieldName string, errMsg string) *Error
- func (v *Validation) Tel(obj interface{}, key string) *Result
- func (v *Validation) Valid(obj interface{}) (b bool, err error)
- func (v *Validation) ZipCode(obj interface{}, key string) *Result
- type Validator
- type ZipCode
Constants ¶
const (
// ValidTag struct tag
ValidTag = "valid"
)
Variables ¶
var CanSkipFuncs = map[string]struct{}{
"Email": {},
"IP": {},
"Mobile": {},
"Tel": {},
"Phone": {},
"ZipCode": {},
}
CanSkipFuncs will skip valid if RequiredFirst is true and the struct field's value is empty
var ( // ErrInt64On32 show 32 bit platform not support int64 ErrInt64On32 = fmt.Errorf("not support int64 on 32-bit platform") )
var MessageTmpls = map[string]string{
"Required": "不能为空",
"Min": "请输入大于%d的值",
"Max": "请输入小于%d的值",
"Range": "范围在[%d-%d]之间",
"MinSize": "长度不能小于%d",
"MaxSize": "长度不能大于%d",
"Length": "长度必须为%d位",
"Alpha": "必须是有效的阿尔法字符",
"Numeric": "必须是有效的数字字符",
"AlphaNumeric": "必须是有效的字母或数字字符",
"Match": "必须匹配%s",
"NoMatch": "必须不匹配%s",
"AlphaDash": "必须是有效的阿尔法或数字或破折号(-_)字符",
"Email": "请输入正确的Email地址",
"IP": "请输入正确的IP地址",
"Base64": "请输入正确的BASE64字符",
"Mobile": "请输入正确的手机号码",
"Tel": "请输入正确的电话号码",
"Phone": "请输入正确的手机号码或电话号码",
"ZipCode": "Must be valid zipcode",
}
MessageTmpls store commond validate template
Functions ¶
func AddCustomFunc ¶
func AddCustomFunc(name string, f CustomFunc) error
AddCustomFunc Add a custom function to validation The name can not be:
Clear HasErrors ErrorMap Error Check Valid NoMatch
If the name is same with exists function, it will replace the origin valid function
func SetDefaultMessage ¶
Types ¶
type Alpha ¶
type Alpha struct {
Key string
}
Alpha check the alpha
func (Alpha) DefaultMessage ¶
DefaultMessage return the default Length error message
func (Alpha) GetLimitValue ¶
func (a Alpha) GetLimitValue() interface{}
GetLimitValue return the limit value
func (Alpha) IsSatisfied ¶
IsSatisfied judge whether obj is valid
type AlphaDash ¶
AlphaDash check not Alpha
func (AlphaDash) DefaultMessage ¶
DefaultMessage return the default AlphaDash error message
func (AlphaDash) GetLimitValue ¶
func (a AlphaDash) GetLimitValue() interface{}
GetLimitValue return the limit value
type AlphaNumeric ¶
type AlphaNumeric struct {
Key string
}
AlphaNumeric check alpha and number
func (AlphaNumeric) DefaultMessage ¶
func (a AlphaNumeric) DefaultMessage() string
DefaultMessage return the default Length error message
func (AlphaNumeric) GetLimitValue ¶
func (a AlphaNumeric) GetLimitValue() interface{}
GetLimitValue return the limit value
func (AlphaNumeric) IsSatisfied ¶
func (a AlphaNumeric) IsSatisfied(obj interface{}) bool
IsSatisfied judge whether obj is valid
type Base64 ¶
Base64 check struct
func (Base64) DefaultMessage ¶
DefaultMessage return the default Base64 error message
func (Base64) GetLimitValue ¶
func (b Base64) GetLimitValue() interface{}
GetLimitValue return the limit value
type CustomFunc ¶
type CustomFunc func(v *Validation, obj interface{}, key string)
CustomFunc is for custom validate function
type Email ¶
Email check struct
func (Email) DefaultMessage ¶
DefaultMessage return the default Email error message
func (Email) GetLimitValue ¶
func (e Email) GetLimitValue() interface{}
GetLimitValue return the limit value
type Error ¶
type Error struct {
Message, Key, Name, Field, Tmpl string
Value interface{}
LimitValue interface{}
}
Error show the error
type IP ¶
IP check struct
func (IP) DefaultMessage ¶
DefaultMessage return the default IP error message
func (IP) GetLimitValue ¶
func (i IP) GetLimitValue() interface{}
GetLimitValue return the limit value
type Length ¶
Length Requires an array or string to be exactly a given length.
func (Length) DefaultMessage ¶
DefaultMessage return the default Length error message
func (Length) GetLimitValue ¶
func (l Length) GetLimitValue() interface{}
GetLimitValue return the limit value
func (Length) IsSatisfied ¶
IsSatisfied judge whether obj is valid
type Match ¶
Match Requires a string to match a given regex.
func (Match) DefaultMessage ¶
DefaultMessage return the default Match error message
func (Match) GetLimitValue ¶
func (m Match) GetLimitValue() interface{}
GetLimitValue return the limit value
func (Match) IsSatisfied ¶
IsSatisfied judge whether obj is valid
type Max ¶
Max validate struct
func (Max) DefaultMessage ¶
DefaultMessage return the default max error message
func (Max) GetLimitValue ¶
func (m Max) GetLimitValue() interface{}
GetLimitValue return the limit value, Max
func (Max) IsSatisfied ¶
IsSatisfied judge whether obj is valid not support int64 on 32-bit platform
type MaxSize ¶
MaxSize Requires an array or string to be at most a given length.
func (MaxSize) DefaultMessage ¶
DefaultMessage return the default MaxSize error message
func (MaxSize) GetLimitValue ¶
func (m MaxSize) GetLimitValue() interface{}
GetLimitValue return the limit value
func (MaxSize) IsSatisfied ¶
IsSatisfied judge whether obj is valid
type Min ¶
Min check struct
func (Min) DefaultMessage ¶
DefaultMessage return the default min error message
func (Min) GetLimitValue ¶
func (m Min) GetLimitValue() interface{}
GetLimitValue return the limit value, Min
func (Min) IsSatisfied ¶
IsSatisfied judge whether obj is valid not support int64 on 32-bit platform
type MinSize ¶
MinSize Requires an array or string to be at least a given length.
func (MinSize) DefaultMessage ¶
DefaultMessage return the default MinSize error message
func (MinSize) GetLimitValue ¶
func (m MinSize) GetLimitValue() interface{}
GetLimitValue return the limit value
func (MinSize) IsSatisfied ¶
IsSatisfied judge whether obj is valid
type Mobile ¶
Mobile check struct
func (Mobile) DefaultMessage ¶
DefaultMessage return the default Mobile error message
func (Mobile) GetLimitValue ¶
func (m Mobile) GetLimitValue() interface{}
GetLimitValue return the limit value
type NoMatch ¶
NoMatch Requires a string to not match a given regex.
func (NoMatch) DefaultMessage ¶
DefaultMessage return the default NoMatch error message
func (NoMatch) GetLimitValue ¶
func (n NoMatch) GetLimitValue() interface{}
GetLimitValue return the limit value
func (NoMatch) IsSatisfied ¶
IsSatisfied judge whether obj is valid
type Numeric ¶
type Numeric struct {
Key string
}
Numeric check number
func (Numeric) DefaultMessage ¶
DefaultMessage return the default Length error message
func (Numeric) GetLimitValue ¶
func (n Numeric) GetLimitValue() interface{}
GetLimitValue return the limit value
func (Numeric) IsSatisfied ¶
IsSatisfied judge whether obj is valid
type Phone ¶
Phone just for chinese telephone or mobile phone number
func (Phone) DefaultMessage ¶
DefaultMessage return the default Phone error message
func (Phone) GetLimitValue ¶
func (p Phone) GetLimitValue() interface{}
GetLimitValue return the limit value
func (Phone) IsSatisfied ¶
IsSatisfied judge whether obj is valid
type Range ¶
Range Requires an integer to be within Min, Max inclusive.
func (Range) DefaultMessage ¶
DefaultMessage return the default Range error message
func (Range) GetLimitValue ¶
func (r Range) GetLimitValue() interface{}
GetLimitValue return the limit value, Max
func (Range) IsSatisfied ¶
IsSatisfied judge whether obj is valid not support int64 on 32-bit platform
type Required ¶
type Required struct {
Key string
}
Required struct
func (Required) DefaultMessage ¶
DefaultMessage return the default error message
func (Required) GetLimitValue ¶
func (r Required) GetLimitValue() interface{}
GetLimitValue return nil now
func (Required) IsSatisfied ¶
IsSatisfied judge whether obj has value
type Result ¶
Result is returned from every validation method. It provides an indication of success, and a pointer to the Error (if any).
type Tel ¶
Tel check telephone struct
func (Tel) DefaultMessage ¶
DefaultMessage return the default Tel error message
func (Tel) GetLimitValue ¶
func (t Tel) GetLimitValue() interface{}
GetLimitValue return the limit value
type ValidFunc ¶
type ValidFunc struct { Name string Params []interface{} }
ValidFunc Valid function type
type Validation ¶
type Validation struct { // if this field set true, in struct tag valid // if the struct field vale is empty // it will skip those valid functions, see CanSkipFuncs RequiredFirst bool Errors []*Error ErrorsMap map[string][]*Error }
A Validation context manages data validation and error messages.
func (*Validation) AddError ¶
func (v *Validation) AddError(key, message string)
AddError adds independent error message for the provided key
func (*Validation) Alpha ¶
func (v *Validation) Alpha(obj interface{}, key string) *Result
Alpha Test that the obj is [a-zA-Z] if type is string
func (*Validation) AlphaDash ¶
func (v *Validation) AlphaDash(obj interface{}, key string) *Result
AlphaDash Test that the obj is [0-9a-zA-Z_-] if type is string
func (*Validation) AlphaNumeric ¶
func (v *Validation) AlphaNumeric(obj interface{}, key string) *Result
AlphaNumeric Test that the obj is [0-9a-zA-Z] if type is string
func (*Validation) Base64 ¶
func (v *Validation) Base64(obj interface{}, key string) *Result
Base64 Test that the obj is base64 encoded if type is string
func (*Validation) CanSkipAlso ¶
func (v *Validation) CanSkipAlso(skipFunc string)
func (*Validation) Check ¶
func (v *Validation) Check(obj interface{}, checks ...Validator) *Result
Check Apply a group of validators to a field, in order, and return the ValidationResult from the first one that fails, or the last one that succeeds.
func (*Validation) Email ¶
func (v *Validation) Email(obj interface{}, key string) *Result
Email Test that the obj is email address if type is string
func (*Validation) Error ¶
func (v *Validation) Error(message string, args ...interface{}) *Result
Error Add an error to the validation context.
func (*Validation) ErrorMap ¶
func (v *Validation) ErrorMap() map[string][]*Error
ErrorMap Return the errors mapped by key. If there are multiple validation errors associated with a single key, the first one "wins". (Typically the first validation will be the more basic).
func (*Validation) HasErrors ¶
func (v *Validation) HasErrors() bool
HasErrors Has ValidationError nor not.
func (*Validation) IP ¶
func (v *Validation) IP(obj interface{}, key string) *Result
IP Test that the obj is IP address if type is string
func (*Validation) Length ¶
func (v *Validation) Length(obj interface{}, n int, key string) *Result
Length Test that the obj is same length to n if type is string or slice
func (*Validation) Match ¶
func (v *Validation) Match(obj interface{}, regex *regexp.Regexp, key string) *Result
Match Test that the obj matches regexp if type is string
func (*Validation) Max ¶
func (v *Validation) Max(obj interface{}, max int, key string) *Result
Max Test that the obj is less than max if obj's type is int
func (*Validation) MaxSize ¶
func (v *Validation) MaxSize(obj interface{}, max int, key string) *Result
MaxSize Test that the obj is shorter than max size if type is string or slice
func (*Validation) Min ¶
func (v *Validation) Min(obj interface{}, min int, key string) *Result
Min Test that the obj is greater than min if obj's type is int
func (*Validation) MinSize ¶
func (v *Validation) MinSize(obj interface{}, min int, key string) *Result
MinSize Test that the obj is longer than min size if type is string or slice
func (*Validation) Mobile ¶
func (v *Validation) Mobile(obj interface{}, key string) *Result
Mobile Test that the obj is chinese mobile number if type is string
func (*Validation) NoMatch ¶
func (v *Validation) NoMatch(obj interface{}, regex *regexp.Regexp, key string) *Result
NoMatch Test that the obj doesn't match regexp if type is string
func (*Validation) Numeric ¶
func (v *Validation) Numeric(obj interface{}, key string) *Result
Numeric Test that the obj is [0-9] if type is string
func (*Validation) Phone ¶
func (v *Validation) Phone(obj interface{}, key string) *Result
Phone Test that the obj is chinese mobile or telephone number if type is string
func (*Validation) Range ¶
func (v *Validation) Range(obj interface{}, min, max int, key string) *Result
Range Test that the obj is between mni and max if obj's type is int
func (*Validation) RecursiveValid ¶
func (v *Validation) RecursiveValid(objc interface{}) (bool, error)
RecursiveValid Recursively validate a struct. Step1: Validate by v.Valid Step2: If pass on step1, then reflect obj's fields Step3: Do the Recursively validation to all struct or struct pointer fields
func (*Validation) Required ¶
func (v *Validation) Required(obj interface{}, key string) *Result
Required Test that the argument is non-nil and non-empty (if string or list)
func (*Validation) SetError ¶
func (v *Validation) SetError(fieldName string, errMsg string) *Error
SetError Set error message for one field in ValidationError
func (*Validation) Tel ¶
func (v *Validation) Tel(obj interface{}, key string) *Result
Tel Test that the obj is chinese telephone number if type is string
func (*Validation) Valid ¶
func (v *Validation) Valid(obj interface{}) (b bool, err error)
Valid Validate a struct. the obj parameter must be a struct or a struct pointer
func (*Validation) ZipCode ¶
func (v *Validation) ZipCode(obj interface{}, key string) *Result
ZipCode Test that the obj is chinese zip code if type is string
type Validator ¶
type Validator interface { IsSatisfied(interface{}) bool DefaultMessage() string GetKey() string GetLimitValue() interface{} }
Validator interface
type ZipCode ¶
ZipCode check the zip struct
func (ZipCode) DefaultMessage ¶
DefaultMessage return the default Zip error message
func (ZipCode) GetLimitValue ¶
func (z ZipCode) GetLimitValue() interface{}
GetLimitValue return the limit value