-
-
Save qiangxue/580c98c1f59e97849bc8b626c2d3245e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That is perfect!!! Cannot think of anything else to make it better. Thanks!!!