[Go] Package of validators and sanitizers for strings, numerics, slices and structs
[Go] Package of validators and sanitizers for strings, numerics, slices and structs
A package of validators and sanitizers for strings, structs and collections. Based on validator.js.
Make sure that Go is installed on your computer. Type the following command in your terminal:
go get github.com/asaskevich/govalidator/v12
or you can get specified release of the package with gopkg.in:
go get gopkg.in/asaskevich/govalidator.v12
After it the package is ready to use.
Add following line in your *.go file:
import "github.com/asaskevich/govalidator/v12"
If you are unhappy to use long govalidator, you can do something like this:
import (
valid "github.com/asaskevich/govalidator/v12"
)
SetFieldsRequiredByDefault causes validation to fail when struct fields do not include validations or are not explicitly marked as exempt (using valid:"-" or valid:"email,optional"). A good place to activate this is a package init function or the main() function.
SetNilPtrAllowedByRequired causes validation to pass when struct fields marked by required are set to nil. This is disabled by default for consistency, but some packages that need to be able to determine between nil and zero value state can use this. If disabled, both nil and zero values cause validation errors.
import "github.com/asaskevich/govalidator/v11"
func init() {
govalidator.SetFieldsRequiredByDefault(true)
}
Here's some code to explain it:
// this struct definition will fail govalidator.ValidateStruct() (and the field values do not matter):
type exampleStruct struct {
Name string ``
Email string `valid:"email"`
}
// this, however, will only fail when Email is empty or an invalid email address:
type exampleStruct2 struct {
Name string `valid:"-"`
Email string `valid:"email"`
}
// lastly, this will only fail when Email is an invalid email address but not when it's empty:
type exampleStruct2 struct {
Name string `valid:"-"`
Email string `valid:"email,optional"`
}
A context was added as the second parameter, for structs this is the object being validated – this makes dependent validation possible.
import "github.com/asaskevich/govalidator/v11"
// old signature
func(i interface{}) bool
// new signature
func(i interface{}, o interface{}) bool
Adding a custom validator
This was changed to prevent data races when accessing custom validators.
import "github.com/asaskevich/govalidator/v11"
// before
govalidator.CustomTypeTagMap["customByteArrayValidator"] = func(i interface{}, o interface{}) bool {
// ...
}
// after
govalidator.CustomTypeTagMap.Set("customByteArrayValidator", func(i interface{}, o interface{}) bool {
// ...
})
…
println(govalidator.IsURL(`http://user@pass:domain.com/path/page`))
IsType
println(govalidator.IsType("Bob", "string"))
println(govalidator.IsType(1, "int"))
i := 1
println(govalidator.IsType(&i, "*int"))
IsType can be used through the tag type which is essential for map validation:
type User struct {
Name string `valid:"type(string)"`
Age int `valid:"type(int)"`
Meta interface{} `valid:"type(string)"`
}
result, err := govalidator.ValidateStruct(User{"Bob", 20, "meta"})
if err != nil {
println("error: " + err.Error())
}
println(result)
ToString
type User struct {
FirstName string
LastName string
}
str := govalidator.ToString(&User{"John", "Juan"})
println(str)
Each, Map, Filter, Count for slices
Each iterates over the slice/array and calls Iterator for every item
data := []interface{}{1, 2, 3, 4, 5}
var fn govalidator.Iterator = func(value interface{}, index int) {
println(value.(int))
}
govalidator.Each(data, fn)
data := []interface{}{1, 2, 3, 4, 5}
var fn govalidator.ResultIterator = func(value interface{}, index int) interface{} {
return value.(int) * 3
}
_ = govalidator.Map(data, fn) // result = []interface{}{1, 6, 9, 12, 15}
data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var fn govalidator.ConditionIterator = func(value interface{}, index int) bool {
return value.(int)%2 == 0
}
_ = govalidator.Filter(data, fn) // result = []interface{}{2, 4, 6, 8, 10}
_ = govalidator.Count(data, fn) // result = 5
ValidateStruct #2
If you want to validate structs, you can use tag valid for any field in your structure. All validators used with this field in one tag are separated by comma. If you want to skip validation, place - in your tag. If you need a validator that is not on the list below, you can add it like this:
govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool {
return str == "duck"
})
For completely custom validators (interface-based), see below.
Here is a list of available validators for struct fields (validator - used function):
…
Validators with parameters
"range(min|max)": Range,
"length(min|max)": ByteLength,
"runelength(min|max)": RuneLength,
"stringlength(min|max)": StringLength,
"matches(pattern)": StringMatches,
"in(string1|string2|...|stringN)": IsIn,
"rsapub(keylength)" : IsRsaPub,
"minstringlength(int): MinStringLength,
"maxstringlength(int): MaxStringLength,
Validators with parameters for any type
"type(type)": IsType,
And here is small example of usage:
…
ValidateMap #2
If you want to validate maps, you can use the map to be validated and a validation map that contain the same tags used in ValidateStruct, both maps have to be in the form map[string]interface{}
So here is small example of usage:
var mapTemplate = map[string]interface{}{
"name":"required,alpha",
"family":"required,alpha",
"email":"required,email",
"cell-phone":"numeric",
"address":map[string]interface{}{
"line1":"required,alphanum",
"line2":"alphanum",
"postal-code":"numeric",
},
}
var inputMap = map[string]interface{}{
"name":"Bob",
"family":"Smith",
"email":"[email protected]",
"address":map[string]interface{}{
"line1":"",
"line2":"",
"postal-code":"",
},
}
result, err := govalidator.ValidateMap(inputMap, mapTemplate)
if err != nil {
println("error: " + err.Error())
}
println(result)
WhiteList
// Remove all characters from string ignoring characters between "a" and "z"
println(govalidator.WhiteList("a3a43a5a4a3a2a23a4a5a4a3a4", "a-z") == "aaaaaaaaaaaa")
Custom validation functions
Custom validation using your own domain specific validators is also available - here's an example of how to use it:
…
Loop over Error()
By default .Error() returns all errors in a single String. To access each error you can do this:
if err != nil {
errs := err.(govalidator.Errors).Errors()
for _, e := range errs {
fmt.Println(e.Error())
}
}
Custom error messages
Custom error messages are supported via annotations by adding the ~ separator - here's an example of how to use it:
type Ticket struct {
Id int64 `json:"id"`
FirstName string `json:"firstname" valid:"required~First name is blank"`
}
Documentation is available here: godoc.org. Full information about code coverage is also available here: govalidator on gocover.io.
If you do have a contribution to the package, feel free to create a Pull Request or an Issue.
If you don't know what to do, there are some features and functions that need to be done
ValidateStruct and add newIsFQDN, IsIMEI, IsPostalCode, IsISIN, IsISRC etcFeel free to create what you want, but keep in mind when you implement new features:
This project exists thanks to all the people who contribute. [Contribute].
Thank you to all our backers! [Become a backer]
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]
No open issues yet, or sync has not completed.