Skip to main content

Validate

What is schema.Validate()?

To validate your data you can use the schema.Validate() function. The function signature looks like this:

schema.Validate(dataPointer, options...)

This works with any Zog Schema:

// string
data := "test"
z.String().Min(3).Validate(&data)
// structs
user := User{Name: "test"}
z.Struct(z.Schema{"name": z.String().Min(3)}).Validate(&user)

Required and Zero Values

One quirk of schema.Validate() is that it will consider zero values as invalid if the schema is required. For example:

var data int
z.Int().Required().Validate(&data) // Error: int is required
data = 0
z.Int().Required().Validate(&data) // Error: int is required

To fix this you can use a pointer:

var data *int
z.Ptr(z.Int()).NotNil().Validate(&data) // will return a not nil issue
*data = 0
z.Ptr(z.Int()).NotNil().Validate(&data) // No issues will be returned

Struct Validation Pattern

Some people prefer calling validate method on the struct themselves. For that you can use this:

type User struct {
ID int
Name string
}
var userSchema = z.Struct(z.Schema{
"ID": z.Int().Required(),
"name": z.String().Required(),
})

func (u *User) Validate() z.ZogIssueMap {
return userSchema.Validate(u)
}

// in some handler somewhere
user := User{ID: 1, Name: "Alice"}
err := user.Validate()
if err != nil {
fmt.Println(err)
}