A powerful validation library for Go.
- Tag syntax that allows for typed parameters and multiple validation sets.
- Validation of deeply nested structures.
- Extensive list of built-in validators.
- Localized error messages.
- Custom validators.
Just use go get.
go get gopkg.in/typerandom/validator.v0
And then just import the package into your own code.
import (
"gopkg.in/typerandom/validator.v0"
)
- Add
validate
tags to the structure that you want to validate. See Tagging and Validators for more details. - Call
errors := validator.Validate(objectWithValidateTags)
. - Call
errors.Any()
to check if there are any errors. - If there are errors, handle them. Or use
errors.PrintAll()
to print them to console (for debugging). - Questions? Check out the wiki.
package main
import (
"gopkg.in/typerandom/validator.v0"
)
type User struct {
Name string `validate:"min(5),max(16)"`
Email string `validate:"regexp(´^[a-z0-9-]*@[a-z0-9.]*\\.com$´)"`
Age int `validate:"min(18),max(65)"`
}
func main() {
user := &User{
Name: "Bob",
Email: "bobby@tables",
Age: 17,
}
if errs := validator.Validate(user); errs.Any() {
errs.PrintAll()
return
}
print("Hey " + user.Name + "!")
}
Running the example above would output:
Name cannot be shorter than 5 characters.
Email must match pattern '^[a-z0-9-]*@[a-z0-9.]*\.com$'.
Age cannot be less than 18.
Validator is licensed under the MIT license. See LICENSE for the full license text.