validation is a form validation for a data validation and error collecting using Go.
Install:
gogetgithub.com/webx-top/validationTest:
gotestgithub.com/webx-top/validationDirect Use:
import (
"github.com/webx-top/validation""log"
)
typeUserstruct {
NamestringAgeint
}
funcmain() {
u:=User{"man", 40}
valid:=validation.New()
valid.Required(u.Name, "name")
valid.MaxSize(u.Name, 15, "nameMax")
valid.Range(u.Age, 0, 140, "age")
ifvalid.HasError() {
// validation does not pass// print invalid messagefor_, err:=rangevalid.Errors {
log.Println(err.Key, err.Message)
}
}
// or use like thisifv:=valid.Max(u.Age, 140); !v.Ok {
log.Println(v.Error.Key, v.Error.Message)
}
}Struct Tag Use:
import (
"github.com/webx-top/validation"
)
// validation function follow with "valid" tag// functions divide with ";"// parameters in parentheses "()" and divide with ","// Match function's pattern string must in "//"typeUserstruct {
IdintNamestring`valid:"required;match(/^(test)?\\w*@;com$/)"`Ageint`valid:"required;range(1, 140)"`
}
typeProfilestruct {
IdintEmailstring`valid:"required;match(/^\\w+@coscms\\.com$/)"`Addrstring`valid:"required"`
}
typeNotValidstruct {
AstringBstring
}
typeGroupstruct {
IdintUser*ProfileNotValid`valid:"-"`//valid标签设为“-”,意味着跳过此项不查询其成员
}
funcmain() {
valid:=validation.New()
u:=User{Name: "test", Age: 40}
b, err:=valid.Valid(u) //检查所有字段//b, err := valid.Valid(u, "Name", "Age") //检查指定字段:Name和Ageiferr!=nil {
// handle error
}
if!b {
// validation does not pass// blabla...
}
valid.Clear()
u:=Group{
User: User{Name: "test", Age: 40},
Profile: &Profile{Email:"test@coscms.com",Addr:"address"},
NotValid: NotValid{},
}
b, err:=valid.Valid(u) //检查所有字段//b, err := valid.Valid(u, "User.Name", "Profile.Email") //检查指定字段iferr!=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
BSD License http://creativecommons.org/licenses/BSD/