Validate
⚔ Go package for data validation and filtering. support Map, Struct, Form data. Go通用的数据验证与过滤库,使用简单,内置大部分常用验证、过滤器,支持自定义验证器、自定义消息、字段翻译。
Install / Use
/learn @gookit/ValidateREADME
Validate
validate is a generic Go data validate and filter tool library.
- Support quick validate
Map,Struct,Request(Form,JSON,url.Values,UploadedFile) data- Validating
http.Requestautomatically collects data based on the requestContent-Typevalue - Supports checking each child value in a slice. eg:
v.StringRule("tags.*", "required|string")
- Validating
- Support filter/sanitize/convert data before validate
- Support add custom filter/validator func
- Support scene settings, verify different fields in different scenes
- Support custom error messages, field translates.
- Can use
message,labeltags in struct
- Can use
- Customizable i18n aware error messages, built in
en,zh-CN,zh-TW - Built-in common data type filter/converter. see Built In Filters
- Many commonly used validators have been built in(> 70), see Built In Validators
- Can use
validatein any frameworks, such as Gin, Echo, Chi and more - Supports direct use of rules to validate value. eg:
validate.Val("xyz@mail.com", "required|email")
中文说明
中文说明请查看 README.zh-CN
Go Doc
Validate Struct
Use the validate tag of the structure, you can quickly config a structure.
Config the struct use tags
Field translations and error messages for structs can be quickly configured using the message and label tags.
- Support configuration field mapping through structure tag, read the value of
jsontag by default - Support configuration error message via structure's
messagetag - Support configuration field translation via structure's
labeltag
package main
import (
"fmt"
"time"
"github.com/gookit/validate"
)
// UserForm struct
type UserForm struct {
Name string `validate:"required|min_len:7" message:"required:{field} is required" label:"User Name"`
Email string `validate:"email" message:"email is invalid" label:"User Email"`
Age int `validate:"required|int|min:1|max:99" message:"int:age must int|min:age min value is 1"`
CreateAt int `validate:"min:1"`
Safe int `validate:"-"`
UpdateAt time.Time `validate:"required" message:"update time is required"`
Code string `validate:"customValidator"`
// ExtInfo nested struct
ExtInfo struct{
Homepage string `validate:"required" label:"Home Page"`
CityName string
} `validate:"required" label:"Home Page"`
}
// CustomValidator custom validator in the source struct.
func (f UserForm) CustomValidator(val string) bool {
return len(val) == 4
}
Config validate use struct methods
validate provides extended functionality:
The struct can implement three interfaces methods, which is convenient to do some customization:
ConfigValidation(v *Validation)will be called after the validator instance is createdMessages() map[string]stringcan customize the validator error messageTranslates() map[string]stringcan customize field translation
package main
import (
"fmt"
"time"
"github.com/gookit/validate"
)
// UserForm struct
type UserForm struct {
Name string `validate:"required|min_len:7"`
Email string `validate:"email"`
Age int `validate:"required|int|min:1|max:99"`
CreateAt int `validate:"min:1"`
Safe int `validate:"-"`
UpdateAt time.Time `validate:"required"`
Code string `validate:"customValidator"`
// ExtInfo nested struct
ExtInfo struct{
Homepage string `validate:"required"`
CityName string
} `validate:"required"`
}
// CustomValidator custom validator in the source struct.
func (f UserForm) CustomValidator(val string) bool {
return len(val) == 4
}
// ConfigValidation config the Validation
// eg:
// - define validate scenes
func (f UserForm) ConfigValidation(v *validate.Validation) {
v.WithScenes(validate.SValues{
"add": []string{"ExtInfo.Homepage", "Name", "Code"},
"update": []string{"ExtInfo.CityName", "Name"},
})
}
// Messages you can custom validator error messages.
func (f UserForm) Messages() map[string]string {
return validate.MS{
"required": "oh! the {field} is required",
"email": "email is invalid",
"Name.required": "message for special field",
"Age.int": "age must int",
"Age.min": "age min value is 1",
}
}
// Translates you can custom field translates.
func (f UserForm) Translates() map[string]string {
return validate.MS{
"Name": "User Name",
"Email": "User Email",
"ExtInfo.Homepage": "Home Page",
}
}
Create and validating
Can use validate.Struct(ptr) quick create a validation instance. then call v.Validate() for validating.
package main
import (
"fmt"
"github.com/gookit/validate"
)
func main() {
u := &UserForm{
Name: "inhere",
}
v := validate.Struct(u)
// v := validate.New(u)
if v.Validate() { // validate ok
// do something ...
} else {
fmt.Println(v.Errors) // all error messages
fmt.Println(v.Errors.One()) // returns a random error message text
fmt.Println(v.Errors.OneError()) // returns a random error
fmt.Println(v.Errors.Field("Name")) // returns error messages of the field
}
}
Validate Map
You can also validate a MAP data directly.
package main
import (
"fmt"
"github.com/gookit/validate"
)
func main() {
m := map[string]any{
"name": "inhere",
"age": 100,
"oldSt": 1,
"newSt": 2,
"email": "some@email.com",
"tags": []string{"go", "php", "java"},
}
v := validate.Map(m)
// v := validate.New(m)
v.AddRule("name", "required")
v.AddRule("name", "minLen", 7)
v.AddRule("age", "max", 99)
v.AddRule("age", "min", 1)
v.AddRule("email", "email")
// can also
v.StringRule("age", "required|int|min:1|max:99")
v.StringRule("name", "required|minLen:7")
v.StringRule("tags", "required|slice|minlen:1")
// feat: support check sub-item in slice
v.StringRule("tags.*", "required|string|min_len:7")
// v.WithScenes(map[string]string{
// "create": []string{"name", "email"},
// "update": []string{"name"},
// })
if v.Validate() { // validate ok
safeData := v.SafeData()
// do something ...
} else {
fmt.Println(v.Errors) // all error messages
fmt.Println(v.Errors.One()) // returns a random error message text
}
}
Validate Request
If it is an HTTP request, you can quickly validate the data and pass the verification. Then bind the secure data to the structure.
package main
import (
"fmt"
"net/http"
"time"
"github.com/gookit/validate"
)
// UserForm struct
type UserForm struct {
Name string
Email string
Age int
CreateAt int
Safe int
UpdateAt time.Time
Code string
}
func main() {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data, err := validate.FromRequest(r)
if err != nil {
panic(err)
}
v := data.Create()
// setting rules
v.FilterRule("age", "int") // convert value to int
v.AddRule("name", "required")
v.AddRule("name", "minLen", 7)
v.AddRule("age", "max", 99)
v.StringRule("code", `required|regex:\d{4,6}`)
if v.Validate() { // validate ok
// safeData := v.SafeData()
userForm := &UserForm{}
v.BindSafeData(userForm)
// do something ...
fmt.Println(userForm.Name)
} else {
fmt.Println(v.Errors) // all error messages
fmt.Println(v.Errors.One()) // returns a random error message text
}
})
http.ListenAndServe(":8090", handler)
}
Quick Method
Quick create Validation instance.
New(data any, scene ...string) *ValidationRequest(r *http.Request) *ValidationJSON(s string, scene ...string) *ValidationStruct(s any, scene ...string) *ValidationMap(m map[string]any, scene ...string) *Validation
Quick create DataFace instance.
FromMap(m map[string]any) *MapDataFromStruct(s any) (*StructData, error)FromJSON(s string) (*MapData, error)FromJSONBytes(bs []byte) (*MapData, error)FromURLValues(values url.Values) *FormDataFromRequest(r *http.Request, maxMemoryLimit ...int64) (DataFace, error)
Create
ValidationfromDataFace
d := FromMap(map[string]any{"key": "val"})
v := d.Validation()
Methods In Validation
func (v *Validation) Validate(scene ...string) boolDo validating and return is success.func (v *Validation) ValidateE(scene ...string) ErrorsDo validating and return error.
More Usage
Validate Error
v.Errors is map data, top key is field name, value is map[string]string.
// do validating
if v.Validate() {
return nil
}
// get errors
es := v.Errors
// check
es.Empty() // bool
// returns an random error, if no error returns nil
fmt.Println(v.Errors.OneError())
fmt.Println(v.Errors.ErrOrNil())
fmt.Println(v.Errors) // all error messages
fmt.Println(v.Errors.One()) // returns a random error message text
fmt.Println(v.Errors.Field("Name")) // returns error messages of the field
Encode to JSON:
StopOnError=true(default), will only one error
{
"field1": {
"required": "error msg0"
}
}
- if
StopOnError=false, will get mul
Related Skills
openhue
344.4kControl Philips Hue lights and scenes via the OpenHue CLI.
sag
344.4kElevenLabs text-to-speech with mac-style say UX.
weather
344.4kGet current weather and forecasts via wttr.in or Open-Meteo
tweakcc
1.5kCustomize Claude Code's system prompts, create custom toolsets, input pattern highlighters, themes/thinking verbs/spinners, customize input box & user message styling, support AGENTS.md, unlock private/unreleased features, and much more. Supports both native/npm installs on all platforms.
