Skip to content

Instantly share code, notes, and snippets.

@qiangxue
Created February 11, 2017 01:56
Show Gist options
  • Save qiangxue/580c98c1f59e97849bc8b626c2d3245e to your computer and use it in GitHub Desktop.
Save qiangxue/580c98c1f59e97849bc8b626c2d3245e to your computer and use it in GitHub Desktop.
package validation_test
import (
"fmt"
"regexp"
"github.com/go-ozzo/ozzo-validation"
"github.com/go-ozzo/ozzo-validation/is"
)
type Address struct {
Street string
City string
State string
Zip string
}
type Customer struct {
Name string
Gender string
Email string
Address Address
}
func (a Address) Validate() error {
return validation.ValidateStruct(&a,
// Street cannot be empty, and the length must between 5 and 50
validation.Field(&a.Street, validation.Required, validation.Length(5, 50)),
// City cannot be empty, and the length must between 5 and 50
validation.Field(&a.City, validation.Required, validation.Length(5, 50)),
// State cannot be empty, and must be a string consisting of two letters in upper case
validation.Field(&a.State, validation.Required, validation.Match(regexp.MustCompile("^[A-Z]{2}$"))),
// State cannot be empty, and must be a string consisting of five digits
validation.Field(&a.Zip, validation.Required, validation.Match(regexp.MustCompile("^[0-9]{5}$"))),
)
}
func (c Customer) Validate() error {
return validation.ValidateStruct(&c,
// Name cannot be empty, and the length must be between 5 and 20.
validation.Field(&c.Name, validation.Required, validation.Length(5, 20)),
// Gender is optional, and should be either "Female" or "Male".
validation.Field(&c.Gender, validation.In("Female", "Male")),
// Email cannot be empty and should be in a valid email format.
validation.Field(&c.Email, validation.Required, is.Email),
// Validate Address using its own validation rules
validation.Field(&c.Address),
)
}
func Example() {
c := Customer{
Name: "Qiang Xue",
Email: "q",
Address: Address{
Street: "123 Main Street",
City: "Unknown",
State: "Virginia",
Zip: "12345",
},
}
err := c.Validate() // or alternatively, err := validation.Validate(c)
fmt.Println(err)
// Output:
// Address: (State: must be in a valid format.); Email: must be a valid email address.
}
@msaron
Copy link

msaron commented Feb 11, 2017

That is perfect!!! Cannot think of anything else to make it better. Thanks!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment