Skip to main content

Validation

Validation runs before every insert and update, an Upsert included. A failure stops the write. It runs with hooks, so bulk writes and ant.WithoutHooks skip it.

Add a rule to a field​

b.Validate attaches a rule typed to one field. The validate package has common rules.

type Signup struct {
ID int64
Name string
Email string
Age int
}

func (Signup) Configure(b *ant.ModelBuilder[Signup]) {
b.Validate(&Signups.Name, validate.All(validate.Required[string](), validate.MaxLength(50)))
b.Validate(&Signups.Email, validate.Email)
b.Validate(&Signups.Age, validate.Range(0, 150))
}

var Signups = ant.Fields[Signup]()
RuleChecks
validate.Required[V]()Not the zero value
validate.EmailA valid address
validate.MinLength(n), validate.MaxLength(n)String length
validate.Range(low, high)Between two values, both included
validate.OneOf(a, b, c)One of these
validate.Matches(pattern)Matches a *regexp.Regexp
validate.All(rules...)All of them

A rule is a func(V) error:

func noSpaces(s string) error {
if strings.Contains(s, " ") {
return errors.New("must not contain spaces")
}

return nil
}

Check rules that span fields​

A rule across several fields goes in a Validate method on the model. It runs on insert and update.

func (s *Signup) Validate(ctx context.Context) error {
if s.Age < 18 && s.Email == "" {
return errors.New("minors need a parent's email")
}

return nil
}

Read the error​

A failed field rule returns an *ant.ValidationError naming the model and field. It wraps the rule's error, so errors.Is works with validate.ErrRequired and your own errors.

err := db.Signups.Insert(ctx, &Signup{Email: "a@example.com"})

var invalid *ant.ValidationError

if errors.As(err, &invalid) {
fmt.Println(invalid.Model, invalid.Field, invalid.Err) // Signup Name is required
}

An error from a Validate method is returned as it is, not wrapped.

Return validation errors to an API client​

Map a ValidationError to a 422 that names the field:

func create(w http.ResponseWriter, r *http.Request) {
signup := &Signup{Name: r.FormValue("name"), Email: r.FormValue("email")}

err := db.Signups.Insert(r.Context(), signup)

var invalid *ant.ValidationError

switch {
case errors.As(err, &invalid):
http.Error(w, invalid.Field+": "+invalid.Err.Error(), http.StatusUnprocessableEntity)
case ant.IsUniqueViolation(err):
http.Error(w, "that email is already registered", http.StatusConflict)
case err != nil:
http.Error(w, "internal error", http.StatusInternalServerError)
}
}

Rules cannot replace a database constraint: a rule can pass while another request inserts the same value, and only the unique constraint catches it.