...

Source file src/github.com/go-playground/validator/v10/_examples/custom-validation/main.go

Documentation: github.com/go-playground/validator/v10/_examples/custom-validation

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/go-playground/validator/v10"
     7  )
     8  
     9  // MyStruct ..
    10  type MyStruct struct {
    11  	String string `validate:"is-awesome"`
    12  }
    13  
    14  // use a single instance of Validate, it caches struct info
    15  var validate *validator.Validate
    16  
    17  func main() {
    18  
    19  	validate = validator.New()
    20  	validate.RegisterValidation("is-awesome", ValidateMyVal)
    21  
    22  	s := MyStruct{String: "awesome"}
    23  
    24  	err := validate.Struct(s)
    25  	if err != nil {
    26  		fmt.Printf("Err(s):\n%+v\n", err)
    27  	}
    28  
    29  	s.String = "not awesome"
    30  	err = validate.Struct(s)
    31  	if err != nil {
    32  		fmt.Printf("Err(s):\n%+v\n", err)
    33  	}
    34  }
    35  
    36  // ValidateMyVal implements validator.Func
    37  func ValidateMyVal(fl validator.FieldLevel) bool {
    38  	return fl.Field().String() == "awesome"
    39  }
    40  

View as plain text