Skip to content

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

sh
go get -u github.com/wuhan005/govalid

Then import it in your code:

go
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:

go
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)
    }
}
text
昵称的最后一个字符不能为下划线
用户编号应小于999
邮箱不是合法的电子邮箱格式

What just happened?

  1. Check walked the struct via reflection.
  2. For each field with a valid tag, every rule (;-separated) was resolved against the global Checkers registry and executed in order.
  3. Each failing rule produced an *ErrContext carrying the field name, label, value and a localized message — *ErrContext itself implements the error interface.
  4. ok is true only 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
go
`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:

go
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:

go
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:

go
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?

Released under the MIT License.