Getting Started
This page walks through installing govalid and validating your first struct in under five minutes.
Requirements
- Go 1.16 or later.
- A module-aware project (
go.mod).
Installation
go get -u github.com/wuhan005/govalidThen import it in your code:
import "github.com/wuhan005/govalid"Your first validation
Tag the fields you want to validate with valid and (optionally) label for human-friendly error messages:
package main
import (
"fmt"
"github.com/wuhan005/govalid"
)
func main() {
form := struct {
Name string `valid:"required;username" label:"昵称"`
ID int `valid:"required;min:0;max:999" label:"用户编号"`
Email string `valid:"required;email" label:"邮箱"`
}{
Name: "e99_",
ID: 1990,
Email: "i@github.red.",
}
errs, ok := govalid.Check(form)
if ok {
fmt.Println("All good")
return
}
for _, err := range errs {
fmt.Println(err)
}
}昵称的最后一个字符不能为下划线
用户编号应小于999
邮箱不是合法的电子邮箱格式What just happened?
Checkwalked the struct via reflection.- For each field with a
validtag, every rule (;-separated) was resolved against the globalCheckersregistry and executed in order. - Each failing rule produced an
*ErrContextcarrying the field name, label, value and a localized message —*ErrContextitself implements theerrorinterface. okistrueonly when no rules failed.
Anatomy of a rule
A valid tag is a list of rules separated by ;. A rule is either:
- A bare checker name:
required - A checker with parameters:
min:18,list:admin,editor,viewer
`valid:"required;min:18;max:120"`TIP
Empty strings short-circuit to "ok" for format-style checkers (email, ipv4, mobile, …) so you can opt fields in and out by combining them with required:
type Form struct {
Optional string `valid:"email"` // empty allowed
Required string `valid:"required;email"` // empty rejected
}Custom error messages per field
Use the msg tag to override the entire error message for a field. The first failing rule short-circuits to this message — handy when product copy is more important than fine-grained reasons:
type Form struct {
Password string `valid:"required;minlen:8" label:"密码" msg:"密码长度需在 8-64 之间"`
}Cross-field & business rules
Anything that depends on more than one field belongs in a Validate() error method. govalid invokes it after the tag rules:
type Form struct {
Password string `valid:"required;minlen:8" label:"密码"`
RepeatPassword string `valid:"required" label:"重复密码"`
}
func (f *Form) Validate() error {
if f.Password != f.RepeatPassword {
return errors.New("两次输入的密码不一致")
}
return nil
}See Cross-field & Business Rules for the full contract.
Where to next?
- Core Concepts — how rules, fields and locales fit together.
- Built-in Checkers — the catalog of ready-made rules.
- Custom Checkers — register your own validators in one line.
- Cookbook — copy-pasteable real-world examples.