...

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

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

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/go-playground/locales/en"
     7  	ut "github.com/go-playground/universal-translator"
     8  	"github.com/go-playground/validator/v10"
     9  	en_translations "github.com/go-playground/validator/v10/translations/en"
    10  )
    11  
    12  // User contains user information
    13  type User struct {
    14  	FirstName      string     `validate:"required"`
    15  	LastName       string     `validate:"required"`
    16  	Age            uint8      `validate:"gte=0,lte=130"`
    17  	Email          string     `validate:"required,email"`
    18  	FavouriteColor string     `validate:"iscolor"`                // alias for 'hexcolor|rgb|rgba|hsl|hsla'
    19  	Addresses      []*Address `validate:"required,dive,required"` // a person can have a home and cottage...
    20  }
    21  
    22  // Address houses a users address information
    23  type Address struct {
    24  	Street string `validate:"required"`
    25  	City   string `validate:"required"`
    26  	Planet string `validate:"required"`
    27  	Phone  string `validate:"required"`
    28  }
    29  
    30  // use a single instance , it caches struct info
    31  var (
    32  	uni      *ut.UniversalTranslator
    33  	validate *validator.Validate
    34  )
    35  
    36  func main() {
    37  
    38  	// NOTE: ommitting allot of error checking for brevity
    39  
    40  	en := en.New()
    41  	uni = ut.New(en, en)
    42  
    43  	// this is usually know or extracted from http 'Accept-Language' header
    44  	// also see uni.FindTranslator(...)
    45  	trans, _ := uni.GetTranslator("en")
    46  
    47  	validate = validator.New()
    48  	en_translations.RegisterDefaultTranslations(validate, trans)
    49  
    50  	translateAll(trans)
    51  	translateIndividual(trans)
    52  	translateOverride(trans) // yep you can specify your own in whatever locale you want!
    53  }
    54  
    55  func translateAll(trans ut.Translator) {
    56  
    57  	type User struct {
    58  		Username string `validate:"required"`
    59  		Tagline  string `validate:"required,lt=10"`
    60  		Tagline2 string `validate:"required,gt=1"`
    61  	}
    62  
    63  	user := User{
    64  		Username: "Joeybloggs",
    65  		Tagline:  "This tagline is way too long.",
    66  		Tagline2: "1",
    67  	}
    68  
    69  	err := validate.Struct(user)
    70  	if err != nil {
    71  
    72  		// translate all error at once
    73  		errs := err.(validator.ValidationErrors)
    74  
    75  		// returns a map with key = namespace & value = translated error
    76  		// NOTICE: 2 errors are returned and you'll see something surprising
    77  		// translations are i18n aware!!!!
    78  		// eg. '10 characters' vs '1 character'
    79  		fmt.Println(errs.Translate(trans))
    80  	}
    81  }
    82  
    83  func translateIndividual(trans ut.Translator) {
    84  
    85  	type User struct {
    86  		Username string `validate:"required"`
    87  	}
    88  
    89  	var user User
    90  
    91  	err := validate.Struct(user)
    92  	if err != nil {
    93  
    94  		errs := err.(validator.ValidationErrors)
    95  
    96  		for _, e := range errs {
    97  			// can translate each error one at a time.
    98  			fmt.Println(e.Translate(trans))
    99  		}
   100  	}
   101  }
   102  
   103  func translateOverride(trans ut.Translator) {
   104  
   105  	validate.RegisterTranslation("required", trans, func(ut ut.Translator) error {
   106  		return ut.Add("required", "{0} must have a value!", true) // see universal-translator for details
   107  	}, func(ut ut.Translator, fe validator.FieldError) string {
   108  		t, _ := ut.T("required", fe.Field())
   109  
   110  		return t
   111  	})
   112  
   113  	type User struct {
   114  		Username string `validate:"required"`
   115  	}
   116  
   117  	var user User
   118  
   119  	err := validate.Struct(user)
   120  	if err != nil {
   121  
   122  		errs := err.(validator.ValidationErrors)
   123  
   124  		for _, e := range errs {
   125  			// can translate each error one at a time.
   126  			fmt.Println(e.Translate(trans))
   127  		}
   128  	}
   129  }
   130  

View as plain text