...

Source file src/github.com/go-playground/validator/v10/_examples/struct-map-rules-validation/main.go

Documentation: github.com/go-playground/validator/v10/_examples/struct-map-rules-validation

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/go-playground/validator/v10"
     6  )
     7  
     8  type Data struct {
     9  	Name    string
    10  	Email   string
    11  	Details *Details
    12  }
    13  
    14  type Details struct {
    15  	FamilyMembers *FamilyMembers
    16  	Salary        string
    17  }
    18  
    19  type FamilyMembers struct {
    20  	FatherName string
    21  	MotherName string
    22  }
    23  
    24  type Data2 struct {
    25  	Name string
    26  	Age  uint32
    27  }
    28  
    29  var validate = validator.New()
    30  
    31  func main() {
    32  	validateStruct()
    33  	// output
    34  	// Key: 'Data2.Name' Error:Field validation for 'Name' failed on the 'min' tag
    35  	// Key: 'Data2.Age' Error:Field validation for 'Age' failed on the 'max' tag
    36  
    37  	validateStructNested()
    38  	// output
    39  	// Key: 'Data.Name' Error:Field validation for 'Name' failed on the 'max' tag
    40  	// Key: 'Data.Details.FamilyMembers' Error:Field validation for 'FamilyMembers' failed on the 'required' tag
    41  }
    42  
    43  func validateStruct() {
    44  	data := Data2{
    45  		Name: "leo",
    46  		Age:  1000,
    47  	}
    48  
    49  	rules := map[string]string{
    50  		"Name": "min=4,max=6",
    51  		"Age":  "min=4,max=6",
    52  	}
    53  
    54  	validate.RegisterStructValidationMapRules(rules, Data2{})
    55  
    56  	err := validate.Struct(data)
    57  	fmt.Println(err)
    58  	fmt.Println()
    59  }
    60  
    61  func validateStructNested() {
    62  	data := Data{
    63  		Name:  "11sdfddd111",
    64  		Email: "zytel3301@mail.com",
    65  		Details: &Details{
    66  			Salary: "1000",
    67  		},
    68  	}
    69  
    70  	rules1 := map[string]string{
    71  		"Name":    "min=4,max=6",
    72  		"Email":   "required,email",
    73  		"Details": "required",
    74  	}
    75  
    76  	rules2 := map[string]string{
    77  		"Salary":        "number",
    78  		"FamilyMembers": "required",
    79  	}
    80  
    81  	rules3 := map[string]string{
    82  		"FatherName": "required,min=4,max=32",
    83  		"MotherName": "required,min=4,max=32",
    84  	}
    85  
    86  	validate.RegisterStructValidationMapRules(rules1, Data{})
    87  	validate.RegisterStructValidationMapRules(rules2, Details{})
    88  	validate.RegisterStructValidationMapRules(rules3, FamilyMembers{})
    89  	err := validate.Struct(data)
    90  
    91  	fmt.Println(err)
    92  }
    93  

View as plain text