...

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

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

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/go-playground/validator/v10"
     7  )
     8  
     9  // User contains user information
    10  type User struct {
    11  	FirstName      string     `validate:"required"`
    12  	LastName       string     `validate:"required"`
    13  	Age            uint8      `validate:"gte=0,lte=130"`
    14  	Email          string     `validate:"required,email"`
    15  	Gender         string     `validate:"oneof=male female prefer_not_to"`
    16  	FavouriteColor string     `validate:"iscolor"`                // alias for 'hexcolor|rgb|rgba|hsl|hsla'
    17  	Addresses      []*Address `validate:"required,dive,required"` // a person can have a home and cottage...
    18  }
    19  
    20  // Address houses a users address information
    21  type Address struct {
    22  	Street string `validate:"required"`
    23  	City   string `validate:"required"`
    24  	Planet string `validate:"required"`
    25  	Phone  string `validate:"required"`
    26  }
    27  
    28  // use a single instance of Validate, it caches struct info
    29  var validate *validator.Validate
    30  
    31  func main() {
    32  
    33  	validate = validator.New(validator.WithRequiredStructEnabled())
    34  
    35  	validateStruct()
    36  	validateVariable()
    37  }
    38  
    39  func validateStruct() {
    40  
    41  	address := &Address{
    42  		Street: "Eavesdown Docks",
    43  		Planet: "Persphone",
    44  		Phone:  "none",
    45  	}
    46  
    47  	user := &User{
    48  		FirstName:      "Badger",
    49  		LastName:       "Smith",
    50  		Age:            135,
    51  		Gender:         "male",
    52  		Email:          "Badger.Smith@gmail.com",
    53  		FavouriteColor: "#000-",
    54  		Addresses:      []*Address{address},
    55  	}
    56  
    57  	// returns nil or ValidationErrors ( []FieldError )
    58  	err := validate.Struct(user)
    59  	if err != nil {
    60  
    61  		// this check is only needed when your code could produce
    62  		// an invalid value for validation such as interface with nil
    63  		// value most including myself do not usually have code like this.
    64  		if _, ok := err.(*validator.InvalidValidationError); ok {
    65  			fmt.Println(err)
    66  			return
    67  		}
    68  
    69  		for _, err := range err.(validator.ValidationErrors) {
    70  
    71  			fmt.Println(err.Namespace())
    72  			fmt.Println(err.Field())
    73  			fmt.Println(err.StructNamespace())
    74  			fmt.Println(err.StructField())
    75  			fmt.Println(err.Tag())
    76  			fmt.Println(err.ActualTag())
    77  			fmt.Println(err.Kind())
    78  			fmt.Println(err.Type())
    79  			fmt.Println(err.Value())
    80  			fmt.Println(err.Param())
    81  			fmt.Println()
    82  		}
    83  
    84  		// from here you can create your own error messages in whatever language you wish
    85  		return
    86  	}
    87  
    88  	// save user to database
    89  }
    90  
    91  func validateVariable() {
    92  
    93  	myEmail := "joeybloggs.gmail.com"
    94  
    95  	errs := validate.Var(myEmail, "required,email")
    96  
    97  	if errs != nil {
    98  		fmt.Println(errs) // output: Key: "" Error:Field validation for "" failed on the "email" tag
    99  		return
   100  	}
   101  
   102  	// email ok, move on
   103  }
   104  

View as plain text