### Install ozzo-validation Package Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md Run this command to install the ozzo-validation package. Ensure you have Go 1.13 or above installed. ```bash go get github.com/go-ozzo/ozzo-validation ``` -------------------------------- ### Create Custom Rule with validation.By Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md Convert a function with the `validation.Rule` signature into a validation rule using `validation.By`. This example checks if a string is exactly 'abc'. ```go func checkAbc(value interface{}) error { ss, _ := value.(string) if ss != "abc" { return errors.New("must be abc") } return nil } err := validation.Validate("xyz", validation.By(checkAbc)) fmt.Println(err) // Output: must be abc ``` -------------------------------- ### Create and Use Rule Groups for Maintainability Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md Define a reusable rule group for common validation patterns. This example creates a `NameRule` group for required fields with length constraints, then applies it to struct fields. ```go var NameRule = []validation.Rule{ validation.Required, validation.Length(5, 20), } type User struct { FirstName string LastName string } func (u User) Validate() error { return validation.ValidateStruct(&u, validation.Field(&u.FirstName, NameRule...), validation.Field(&u.LastName, NameRule...), ) } ``` -------------------------------- ### Defining a Validatable Struct with Nested Validation Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md This example shows how to define a `Customer` struct that includes a nested `Address` struct, which also implements the `Validatable` interface. The `Customer.Validate()` method uses `validation.ValidateStruct` to apply rules to its fields, including diving into the `Address` field for its own validation. ```go type Customer struct { Name string Gender string Email string Address Address } 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), ) } ``` ```go c := Customer{ Name: "Qiang Xue", Email: "q", Address: Address{ Street: "123 Main Street", City: "Unknown", State: "Virginia", Zip: "12345", }, } err := c.Validate() fmt.Println(err) ``` ```text // Output: // Address: (State: must be in a valid format.); Email: must be a valid email address. ``` -------------------------------- ### Create and Use a Context-Aware Rule Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md Demonstrates how to create a context-aware rule using `validation.WithContext` and validate a value against it using `validation.ValidateWithContext`. The rule checks if a provided value matches a secret stored in the context. ```go rule := validation.WithContext(func(ctx context.Context, value interface{}) error { if ctx.Value("secret") == value.(string) { return nil } return errors.New("value incorrect") }) value := "xyz" ctx := context.WithValue(context.Background(), "secret", "example") err := validation.ValidateWithContext(ctx, value, rule) fmt.Println(err) // Output: value incorrect ``` -------------------------------- ### Validate a Simple String Value Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md Demonstrates validating a string using multiple rules: required, length, and URL format. Validation stops at the first failed rule. ```go package main import ( "fmt" "github.com/go-ozzo/ozzo-validation/v4" "github.com/go-ozzo/ozzo-validation/v4/is" ) func main() { data := "example" err := validation.Validate(data, validation.Required, // not empty validation.Length(5, 100), // length between 5 and 100 is.URL, // is a valid URL ) fmt.Println(err) // Output: // must be a valid URL } ``` -------------------------------- ### Manually Build and Filter Validation Errors Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md Demonstrates an alternative approach to validation error handling by manually constructing a `validation.Errors` map and then filtering out successful validations. This offers more flexibility in defining error keys. ```go c := Customer{ Name: "Qiang Xue", Email: "q", Address: Address{ State: "Virginia", }, } err := validation.Errors{ "name": validation.Validate(c.Name, validation.Required, validation.Length(5, 20)), "email": validation.Validate(c.Name, validation.Required, is.Email), "zip": validation.Validate(c.Address.Zip, validation.Required, validation.Match(regexp.MustCompile("^[0-9]{5}$ সন"))), }.Filter() fmt.Println(err) // Output: // email: must be a valid email address; zip: cannot be blank. ``` -------------------------------- ### Upgrade Error Message Placeholders (3.x to 4.x) Source: https://github.com/go-ozzo/ozzo-validation/blob/master/UPGRADE.md When upgrading from v3.x to v4.x, change error message placeholders from %v to Go template variables like {{.min}} and {{.max}}. ```go // 3.x lengthRule := validation.Length(2,10).Error("the length must be between %v and %v") // 4.x lengthRule := validation.Length(2,10).Error("the length must be between {{.min}} and {{.max}}") ``` -------------------------------- ### Conditional Validation with validation.When Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md Use `validation.When` to apply validation rules only when a specific condition is met. The `Else` clause can specify rules for when the condition is false. ```go result := validation.ValidateStruct(&a, validation.Field(&a.Unit, validation.When(a.Quantity != "", validation.Required).Else(validation.Nil)), validation.Field(&a.Phone, validation.When(a.Email == "", validation.Required.Error('Either phone or Email is required.')), validation.Field(&a.Email, validation.When(a.Phone == "", validation.Required.Error('Either phone or Email is required.')), ) ``` -------------------------------- ### Simplified Conditional Validation with validation.Required.When Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md A more concise way to express conditional validation using the `validation.Required.When` shortcut. This is useful for required fields that depend on other fields' values. ```go result := validation.ValidateStruct(&a, validation.Field(&a.Unit, validation.Required.When(a.Quantity != ""), validation.Nil.When(a.Quantity == "")), validation.Field(&a.Phone, validation.Required.When(a.Email == "").Error('Either phone or Email is required.')), validation.Field(&a.Email, validation.Required.When(a.Phone == "").Error('Either phone or Email is required.')), ) ``` -------------------------------- ### Define and Validate a Struct Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md Shows how to define validation rules for struct fields using `validation.ValidateStruct`. Each field can have multiple rules applied. ```go type Address struct { Street string City string State string Zip string } 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}$"))), ) } a := Address{ Street: "123", City: "Unknown", State: "Virginia", Zip: "12345", } err := a.Validate() fmt.Println(err) // Output: // Street: the length must be between 5 and 50; State: must be in a valid format. ``` -------------------------------- ### Upgrade Value Validation API (2.x to 3.x) Source: https://github.com/go-ozzo/ozzo-validation/blob/master/UPGRADE.md When upgrading from v2.x to v3.x, replace the Rules.Validate() pattern with validation.Validate() by passing rules directly. ```go data := "example" // 2.x usage rules := validation.Rules{ validation.Required, validation.Length(5, 100), is.URL, } err := rules.Validate(data) // 3.x usage err := validation.Validate(data, validation.Required, validation.Length(5, 100), is.URL, ) ``` -------------------------------- ### Create Custom Rule with Parameters using Closure Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md Use a closure to create a validation rule that accepts additional parameters. This function checks if a string equals a specified value. ```go func stringEquals(str string) validation.RuleFunc { return func(value interface{}) error { s, _ := value.(string) if s != str { return errors.New("unexpected string") } return nil } } err := validation.Validate("xyz", validation.By(stringEquals("abc"))) fmt.Println(err) // Output: unexpected string ``` -------------------------------- ### Marshal Validation Errors to JSON Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md Shows how to marshal validation errors, which are returned as a `validation.Errors` map, into a JSON string. This is useful for API responses. ```go type Address struct { Street string `json:"street"` City string `json:"city"` State string `json:"state"` Zip string `json:"zip"` } // ...perform validation here... err := a.Validate() b, _ := json.Marshal(err) fmt.Println(string(b)) // Output: // {"street":"the length must be between 5 and 50","state":"must be in a valid format"} ``` -------------------------------- ### Apply Rules to Each Element in a Slice Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md The `Each` rule applies a set of validations to every element within a slice, array, or map. This is useful for ensuring all items in a collection meet specific criteria, like email format. ```go type Customer struct { Name string Emails []string } 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)), // Emails are optional, but if given must be valid. validation.Field(&c.Emails, validation.Each(is.Email)), ) } c := Customer{ Name: "Qiang Xue", Emails: []Email{ "valid@example.com", "invalid", }, } err := c.Validate() fmt.Println(err) // Output: // Emails: (1: must be a valid email address.). ``` -------------------------------- ### Validate a Nested Map with Custom Rules Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md Demonstrates validating a nested map structure with specific rules for each key, including required fields, length constraints, email format, and regex matching for nested map fields. ```go c := map[string]interface{}{ "Name": "Qiang Xue", "Email": "q", "Address": map[string]interface{}{ "Street": "123", "City": "Unknown", "State": "Virginia", "Zip": "12345", }, } err := validation.Validate(c, validation.Map( // Name cannot be empty, and the length must be between 5 and 20. validation.Key("Name", validation.Required, validation.Length(5, 20)), // Email cannot be empty and should be in a valid email format. validation.Key("Email", validation.Required, is.Email), // Validate Address using its own validation rules validation.Key("Address", validation.Map( // Street cannot be empty, and the length must between 5 and 50 validation.Key("Street", validation.Required, validation.Length(5, 50)), // City cannot be empty, and the length must between 5 and 50 validation.Key("City", validation.Required, validation.Length(5, 50)), // State cannot be empty, and must be a string consisting of two letters in upper case validation.Key("State", validation.Required, validation.Match(regexp.MustCompile("^[A-Z]{2}$ সন"))), // State cannot be empty, and must be a string consisting of five digits validation.Key("Zip", validation.Required, validation.Match(regexp.MustCompile("^[0-9]{5}$ সন"))), )), ), ) fmt.Println(err) // Output: // Address: (State: must be in a valid format; Street: the length must be between 5 and 50.); Email: must be a valid email address. ``` -------------------------------- ### Define Custom Validation Rule Interface Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md The `validation.Rule` interface requires a single `Validate` method. This method should return an error if the validation fails. ```go // Validate validates a value and returns an error if validation fails. Validate(value interface{}) error ``` -------------------------------- ### Upgrade Struct Validation API (2.x to 3.x) Source: https://github.com/go-ozzo/ozzo-validation/blob/master/UPGRADE.md When upgrading from v2.x to v3.x, replace StructRules with ValidateStruct() for defining and performing struct validations. ```go // 2.x usage err := validation.StructRules{}. Add("Street", validation.Required, validation.Length(5, 50)). Add("City", validation.Required, validation.Length(5, 50)). Add("State", validation.Required, validation.Match(regexp.MustCompile("^\\u005bA-Z]{2}$"))). Add("Zip", validation.Required, validation.Match(regexp.MustCompile("^\\u005b0-9]{5}$"))). Validate(a) // 3.x usage err := validation.ValidateStruct(&a, validation.Field(&a.Street, validation.Required, validation.Length(5, 50)), validation.Field(&a.City, validation.Required, validation.Length(5, 50)), validation.Field(&a.State, validation.Required, validation.Match(regexp.MustCompile("^\\u005bA-Z]{2}$"))), validation.Field(&a.Zip, validation.Required, validation.Match(regexp.MustCompile("^\\u005b0-9]{5}$"))), ) ``` -------------------------------- ### Customizing Default Error Messages Globally Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md Globally customize the default error messages for built-in rules, such as `ErrRequired`, by reassigning them. This change affects all subsequent uses of the rule. ```go validation.ErrRequired = validation.ErrRequired.SetMessage("the value is required") ``` -------------------------------- ### Validate Slice of Validatable Items Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md When validating a slice of items that implement the `validation.Validatable` interface, `validation.Validate` will call the `Validate` method on each non-nil element. Errors from individual elements are collected. ```go addresses := []Address{ Address{State: "MD", Zip: "12345"}, Address{Street: "123 Main St", City: "Vienna", State: "VA", Zip: "12345"}, Address{City: "Unknown", State: "NC", Zip: "123"}, } err := validation.Validate(addresses) fmt.Println(err) // Output: // 0: (City: cannot be blank; Street: cannot be blank.); 2: (Street: cannot be blank; Zip: must be in a valid format.). ``` -------------------------------- ### Customizing Error Messages for Validation Rules Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md Customize the error messages for built-in validation rules by calling the `Error()` method. This allows for more user-friendly error reporting. ```go data := "2123" err := validation.Validate(data, validation.Required.Error("is required"), validation.Match(regexp.MustCompile("^[0-9]{5}$")).Error("must be a string with five digits"), ) fmt.Println(err) ``` -------------------------------- ### Checking for Internal Errors during Validation Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md This snippet demonstrates how to check if an error returned from a validation process is an internal error. Internal errors indicate issues with the validation code itself, not the data being validated. ```go if err := a.Validate(); err != nil { if e, ok := err.(validation.InternalError); ok { // an internal error happened fmt.Println(e.InternalError()) } } ``` -------------------------------- ### Creating Custom Validation Errors with Error Codes Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md Use `validation.NewError()` to create custom validation errors that implement the `Error` interface, providing both an immutable error code and a customizable message. ```go validation.NewError("custom_code", "custom message") ``` -------------------------------- ### Validate Embedded Structs Source: https://github.com/go-ozzo/ozzo-validation/blob/master/README.md When validating a struct that contains embedded structs, `validation.ValidateStruct` treats the fields of the embedded struct as if they belong directly to the containing struct. You can validate embedded fields directly or by validating the embedded struct itself if it implements `validation.Validatable`. ```go type Employee struct { Name string } type Manager struct { Employee Level int } m := Manager{} err := validation.ValidateStruct(&m, validation.Field(&m.Name, validation.Required), validation.Field(&m.Level, validation.Required), ) fmt.Println(err) // Output: // Level: cannot be blank; Name: cannot be blank. ``` ```go func (e Employee) Validate() error { return validation.ValidateStruct(&e, validation.Field(&e.Name, validation.Required), ) } err := validation.ValidateStruct(&m, validation.Field(&m.Employee), validation.Field(&m.Level, validation.Required), ) fmt.Println(err) // Output: // Level: cannot be blank; Name: cannot be blank. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.