This lib uses the Is...
validation functions from the govalidator project.
go get github.com/tiendc/go-validator
type Person struct {
Name string
Birthdate time.Time
Unemployed bool
Salary uint
Rank string
WorkEmail string
}
p := Person{
Name: "",
Unemployed: false,
Rank: "Manager",
Salary: 1000,
}
errs := Validate(
Required(&p.Name),
StrLen(&p.Name, 3, 100).OnError(
SetField("name", nil),
SetCustomKey("ERR_PERSON_NAME_REQUIRED"),
),
Required(&p.Birthdate),
When(!p.Unemployed).Then(
Required(&p.Salary),
// WorkEmail is required and must be valid
Required(&p.WorkEmail),
StrIsEmail(&p.WorkEmail),
// OR use this to produce only one error when the validation fails
Group(
Required(&p.WorkEmail),
StrIsEmail(&p.WorkEmail),
).OnError(...),
StrIn(&p.Rank, "Employee", "Manager", "Director"),
Case(
When(p.Rank == "Manager").Then(NumGT(&p.Salary, 10000)),
When(p.Rank == "Director").Then(NumGT(&p.Salary, 30000)),
).Default(
NumLT(&p.Salary, 10000),
),
).Else(
NumEQ(&p.Salary, 0),
StrEQ(&p.WorkEmail, ""),
),
// OTHERS
// Pass if at least one of the validations passes
OneOf(
// List of validations
),
// Pass if exact one of the validations passes
ExactOneOf(
// List of validations
),
// Pass if none of the validations passes
NotOf(
// List of validations
),
)
for _, e := range errs {
detail, warnErr := e.BuildDetail()
fmt.Printf("%+v\n", detail)
}
- You are welcome to make pull requests for new functions and bug fixes.
- Dao Cong Tien (tiendc)