Golang Engineering Components Field Validator validator's custom fields, structure supplements and custom validation

Golang is a fast, safe, and efficient programming language that is widely used to build high-performance, distributed systems. In Golang, component programming is a very important concept. Component programming can make the code more clear and concise, easy to maintain and expand.

In this article, we will discuss the custom fields, structure supplements and custom validation of the field validator validator in Golang Engineering Components.

1. Custom fields

In validator, we can use existing standard types for verification, or use custom types to achieve more flexible verification. Here is a simple example:

package main

import (
    "github.com/go-playground/validator/v10"
)

type Age int

func (a Age) Validate(fl validator.FieldLevel) bool {
    return a > 0 && a < 100
}

type User struct {
    Name string `validate:"required"`
    Age  Age    `validate:"required,age"`
}

func main() {
    user := &User{
        Name: "John Doe",
        Age:  120,
    }

    validate := validator.New()
    validate.RegisterValidation("age", Age(0).Validate)
    err := validate.Struct(user)

	if err != nil {
        for _, e := range err.(validator.ValidationErrors) {
            fmt.Println(e.StructField())
            fmt.Println(e.Tag())
            fmt.Println(e.Param())
        }
    }
}

In the above example, we defined a custom type called Age and added a Validate method to it for validation. At the same time, in the User structure, we set the label symbol of the Age field to "age", and registered a custom validation function in the validate.RegisterValidation method.

Next, in the main function, we create a user instance and verify it. If the value of the Age field does not meet the rules, an error message will be returned; otherwise, the name, label symbol and error message of each field will be output.

Second, the structure supplement

In validator, in addition to using existing standard types for verification, it also supports using structures to represent complex data types. Here is a simple example:

package main

import (
    "github.com/go-playground/validator/v10"
)

type Address struct {
    Street  string `validate:"required"`
    City    string `validate:"required"`
    Country string `validate:"required"`
}

type User struct {
    Name      string   `validate:"required"`
    Email     string   `validate:"required,email"`
    Addresses []Address
}

func main() {
    user := &User{
        Name:  "John Doe",
        Email: "[email protected]",
        Addresses: []Address{
            {Street: "123 Main St.", City: "Anytown", Country: "USA"},
            {City: "", Country: ""},
        },
    }

    validate := validator.New()
    err := validate.Struct(user)
    
	if err != nil {
        for _, e := range err.(validator.ValidationErrors) {
            fmt.Println(e.StructField())
            fmt.Println(e.Tag())
            fmt.Println(e.Param())
        }
    }
}

In the above example, we defined two structures Address and User, and verified the fields in these two structures respectively. Among them, the User structure contains an Addresses field whose value is a slice of Address type.

Next, in the main function, we create a user instance and pass it to the validate.Struct method for validation. If the verification fails, an error message will be returned; otherwise, the name, label symbol and error message of each field will be output.

3. Custom verification

In validator, in addition to using existing standard types and structures for validation, it also supports the use of custom validators to implement more flexible validation rules. Here is a simple example:

package main

import (
    "github.com/go-playground/validator/v10"
)

func validateUsername(fl validator.FieldLevel) bool {
    username := fl.Field().String()
    return len(username) >= 6 && len(username) <= 20
}

type User struct {
    Name     string `validate:"required"`
    Username string `validate:"required,username"`
}

func main() {
    user := &User{
        Name:     "John Doe",
        Username: "john_doe_123",
    }

    validate := validator.New()
    validate.RegisterValidation("username", validateUsername)
    err := validate.Struct(user)

	if err != nil {
        for _, e := range err.(validator.ValidationErrors) {
            fmt.Println(e.StructField())
            fmt.Println(e.Tag())
            fmt.Println(e.Param())
        }
    }
}

In the above example, we defined a custom validation function called validateUsername and registered it in the validator. At the same time, in the User structure, we set the label symbol of the Username field to "username", indicating that the custom validator is used for validation.

Next, in the main function, we create a user instance and verify it. If the value of the Username field does not meet the rules, an error message will be returned; otherwise, the name, label symbol, and error message of each field will be output.

Four. Summary

This article introduces the custom fields, structure supplements and custom validation of the field validator validator in the Golang Engineering Components chapter. By using the validator library, we can easily verify complex data types effectively and improve the robustness and reliability of the program. Hope this article can be helpful to readers.

Guess you like

Origin blog.csdn.net/SMILY12138/article/details/130967739
Recommended