diff --git a/go-playground/validator/v10/_examples/custom-validation/main.go b/go-playground/validator/v10/_examples/custom-validation/main.go deleted file mode 100644 index 03ddf79..0000000 --- a/go-playground/validator/v10/_examples/custom-validation/main.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "fmt" - - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -// MyStruct .. -type MyStruct struct { - String string `validate:"is-awesome"` -} - -// use a single instance of Validate, it caches struct info -var validate *validator.Validate - -func main() { - - validate = validator.New() - validate.RegisterValidation("is-awesome", ValidateMyVal) - - s := MyStruct{String: "awesome"} - - err := validate.Struct(s) - if err != nil { - fmt.Printf("Err(s):\n%+v\n", err) - } - - s.String = "not awesome" - err = validate.Struct(s) - if err != nil { - fmt.Printf("Err(s):\n%+v\n", err) - } -} - -// ValidateMyVal implements validator.Func -func ValidateMyVal(fl validator.FieldLevel) bool { - return fl.Field().String() == "awesome" -} diff --git a/go-playground/validator/v10/_examples/custom/main.go b/go-playground/validator/v10/_examples/custom/main.go deleted file mode 100644 index 2947b04..0000000 --- a/go-playground/validator/v10/_examples/custom/main.go +++ /dev/null @@ -1,51 +0,0 @@ -package main - -import ( - "database/sql" - "database/sql/driver" - "fmt" - "reflect" - - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -// DbBackedUser User struct -type DbBackedUser struct { - Name sql.NullString `validate:"required"` - Age sql.NullInt64 `validate:"required"` -} - -// use a single instance of Validate, it caches struct info -var validate *validator.Validate - -func main() { - - validate = validator.New() - - // register all sql.Null* types to use the ValidateValuer CustomTypeFunc - validate.RegisterCustomTypeFunc(ValidateValuer, sql.NullString{}, sql.NullInt64{}, sql.NullBool{}, sql.NullFloat64{}) - - // build object for validation - x := DbBackedUser{Name: sql.NullString{String: "", Valid: true}, Age: sql.NullInt64{Int64: 0, Valid: false}} - - err := validate.Struct(x) - - if err != nil { - fmt.Printf("Err(s):\n%+v\n", err) - } -} - -// ValidateValuer implements validator.CustomTypeFunc -func ValidateValuer(field reflect.Value) interface{} { - - if valuer, ok := field.Interface().(driver.Valuer); ok { - - val, err := valuer.Value() - if err == nil { - return val - } - // handle the error how you want - } - - return nil -} diff --git a/go-playground/validator/v10/_examples/dive/main.go b/go-playground/validator/v10/_examples/dive/main.go deleted file mode 100644 index efa5c17..0000000 --- a/go-playground/validator/v10/_examples/dive/main.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "fmt" - - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -// Test ... -type Test struct { - Array []string `validate:"required,gt=0,dive,required"` - Map map[string]string `validate:"required,gt=0,dive,keys,keymax,endkeys,required,max=1000"` -} - -// use a single instance of Validate, it caches struct info -var validate *validator.Validate - -func main() { - - validate = validator.New() - - // registering alias so we can see the differences between - // map key, value validation errors - validate.RegisterAlias("keymax", "max=10") - - var test Test - - val(test) - - test.Array = []string{""} - test.Map = map[string]string{"test > than 10": ""} - val(test) -} - -func val(test Test) { - fmt.Println("testing") - err := validate.Struct(test) - fmt.Println(err) -} diff --git a/go-playground/validator/v10/_examples/gin-upgrading-overriding/main.go b/go-playground/validator/v10/_examples/gin-upgrading-overriding/main.go deleted file mode 100644 index 46fdf2a..0000000 --- a/go-playground/validator/v10/_examples/gin-upgrading-overriding/main.go +++ /dev/null @@ -1,10 +0,0 @@ -package main - -import "github.com/gin-gonic/gin/binding" - -func main() { - - binding.Validator = new(defaultValidator) - - // regular gin logic -} diff --git a/go-playground/validator/v10/_examples/gin-upgrading-overriding/v8_to_v9.go b/go-playground/validator/v10/_examples/gin-upgrading-overriding/v8_to_v9.go deleted file mode 100644 index 4f1fa14..0000000 --- a/go-playground/validator/v10/_examples/gin-upgrading-overriding/v8_to_v9.go +++ /dev/null @@ -1,55 +0,0 @@ -package main - -import ( - "reflect" - "sync" - - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" - "github.com/gin-gonic/gin/binding" -) - -type defaultValidator struct { - once sync.Once - validate *validator.Validate -} - -var _ binding.StructValidator = &defaultValidator{} - -func (v *defaultValidator) ValidateStruct(obj interface{}) error { - - if kindOfData(obj) == reflect.Struct { - - v.lazyinit() - - if err := v.validate.Struct(obj); err != nil { - return err - } - } - - return nil -} - -func (v *defaultValidator) Engine() interface{} { - v.lazyinit() - return v.validate -} - -func (v *defaultValidator) lazyinit() { - v.once.Do(func() { - v.validate = validator.New() - v.validate.SetTagName("binding") - - // add any custom validations etc. here - }) -} - -func kindOfData(data interface{}) reflect.Kind { - - value := reflect.ValueOf(data) - valueType := value.Kind() - - if valueType == reflect.Ptr { - valueType = value.Elem().Kind() - } - return valueType -} diff --git a/go-playground/validator/v10/_examples/simple/main.go b/go-playground/validator/v10/_examples/simple/main.go deleted file mode 100644 index 8586bac..0000000 --- a/go-playground/validator/v10/_examples/simple/main.go +++ /dev/null @@ -1,101 +0,0 @@ -package main - -import ( - "fmt" - - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -// User contains user information -type User struct { - FirstName string `validate:"required"` - LastName string `validate:"required"` - Age uint8 `validate:"gte=0,lte=130"` - Email string `validate:"required,email"` - FavouriteColor string `validate:"iscolor"` // alias for 'hexcolor|rgb|rgba|hsl|hsla' - Addresses []*Address `validate:"required,dive,required"` // a person can have a home and cottage... -} - -// Address houses a users address information -type Address struct { - Street string `validate:"required"` - City string `validate:"required"` - Planet string `validate:"required"` - Phone string `validate:"required"` -} - -// use a single instance of Validate, it caches struct info -var validate *validator.Validate - -func main() { - - validate = validator.New() - - validateStruct() - validateVariable() -} - -func validateStruct() { - - address := &Address{ - Street: "Eavesdown Docks", - Planet: "Persphone", - Phone: "none", - } - - user := &User{ - FirstName: "Badger", - LastName: "Smith", - Age: 135, - Email: "Badger.Smith@gmail.com", - FavouriteColor: "#000-", - Addresses: []*Address{address}, - } - - // returns nil or ValidationErrors ( []FieldError ) - err := validate.Struct(user) - if err != nil { - - // this check is only needed when your code could produce - // an invalid value for validation such as interface with nil - // value most including myself do not usually have code like this. - if _, ok := err.(*validator.InvalidValidationError); ok { - fmt.Println(err) - return - } - - for _, err := range err.(validator.ValidationErrors) { - - fmt.Println(err.Namespace()) - fmt.Println(err.Field()) - fmt.Println(err.StructNamespace()) - fmt.Println(err.StructField()) - fmt.Println(err.Tag()) - fmt.Println(err.ActualTag()) - fmt.Println(err.Kind()) - fmt.Println(err.Type()) - fmt.Println(err.Value()) - fmt.Println(err.Param()) - fmt.Println() - } - - // from here you can create your own error messages in whatever language you wish - return - } - - // save user to database -} - -func validateVariable() { - - myEmail := "joeybloggs.gmail.com" - - errs := validate.Var(myEmail, "required,email") - - if errs != nil { - fmt.Println(errs) // output: Key: "" Error:Field validation for "" failed on the "email" tag - return - } - - // email ok, move on -} diff --git a/go-playground/validator/v10/_examples/struct-level/main.go b/go-playground/validator/v10/_examples/struct-level/main.go deleted file mode 100644 index 7b6f28e..0000000 --- a/go-playground/validator/v10/_examples/struct-level/main.go +++ /dev/null @@ -1,120 +0,0 @@ -package main - -import ( - "fmt" - "reflect" - "strings" - - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -// User contains user information -type User struct { - FirstName string `json:"fname"` - LastName string `json:"lname"` - Age uint8 `validate:"gte=0,lte=130"` - Email string `json:"e-mail" validate:"required,email"` - FavouriteColor string `validate:"hexcolor|rgb|rgba"` - Addresses []*Address `validate:"required,dive,required"` // a person can have a home and cottage... -} - -// Address houses a users address information -type Address struct { - Street string `validate:"required"` - City string `validate:"required"` - Planet string `validate:"required"` - Phone string `validate:"required"` -} - -// use a single instance of Validate, it caches struct info -var validate *validator.Validate - -func main() { - - validate = validator.New() - - // register function to get tag name from json tags. - validate.RegisterTagNameFunc(func(fld reflect.StructField) string { - name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0] - if name == "-" { - return "" - } - return name - }) - - // register validation for 'User' - // NOTE: only have to register a non-pointer type for 'User', validator - // interanlly dereferences during it's type checks. - validate.RegisterStructValidation(UserStructLevelValidation, User{}) - - // build 'User' info, normally posted data etc... - address := &Address{ - Street: "Eavesdown Docks", - Planet: "Persphone", - Phone: "none", - City: "Unknown", - } - - user := &User{ - FirstName: "", - LastName: "", - Age: 45, - Email: "Badger.Smith@gmail", - FavouriteColor: "#000", - Addresses: []*Address{address}, - } - - // returns InvalidValidationError for bad validation input, nil or ValidationErrors ( []FieldError ) - err := validate.Struct(user) - if err != nil { - - // this check is only needed when your code could produce - // an invalid value for validation such as interface with nil - // value most including myself do not usually have code like this. - if _, ok := err.(*validator.InvalidValidationError); ok { - fmt.Println(err) - return - } - - for _, err := range err.(validator.ValidationErrors) { - - fmt.Println(err.Namespace()) // can differ when a custom TagNameFunc is registered or - fmt.Println(err.Field()) // by passing alt name to ReportError like below - fmt.Println(err.StructNamespace()) - fmt.Println(err.StructField()) - fmt.Println(err.Tag()) - fmt.Println(err.ActualTag()) - fmt.Println(err.Kind()) - fmt.Println(err.Type()) - fmt.Println(err.Value()) - fmt.Println(err.Param()) - fmt.Println() - } - - // from here you can create your own error messages in whatever language you wish - return - } - - // save user to database -} - -// UserStructLevelValidation contains custom struct level validations that don't always -// make sense at the field validation level. For Example this function validates that either -// FirstName or LastName exist; could have done that with a custom field validation but then -// would have had to add it to both fields duplicating the logic + overhead, this way it's -// only validated once. -// -// NOTE: you may ask why wouldn't I just do this outside of validator, because doing this way -// hooks right into validator and you can combine with validation tags and still have a -// common error output format. -func UserStructLevelValidation(sl validator.StructLevel) { - - user := sl.Current().Interface().(User) - - if len(user.FirstName) == 0 && len(user.LastName) == 0 { - sl.ReportError(user.FirstName, "fname", "FirstName", "fnameorlname", "") - sl.ReportError(user.LastName, "lname", "LastName", "fnameorlname", "") - } - - // plus can do more, even with different tag than "fnameorlname" -} diff --git a/go-playground/validator/v10/_examples/translations/main.go b/go-playground/validator/v10/_examples/translations/main.go deleted file mode 100644 index b1b7b67..0000000 --- a/go-playground/validator/v10/_examples/translations/main.go +++ /dev/null @@ -1,129 +0,0 @@ -package main - -import ( - "fmt" - - "git.ningdatech.com/ningda/gin_valid/go-playground/locales/en" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" - en_translations "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10/translations/en" -) - -// User contains user information -type User struct { - FirstName string `validate:"required"` - LastName string `validate:"required"` - Age uint8 `validate:"gte=0,lte=130"` - Email string `validate:"required,email"` - FavouriteColor string `validate:"iscolor"` // alias for 'hexcolor|rgb|rgba|hsl|hsla' - Addresses []*Address `validate:"required,dive,required"` // a person can have a home and cottage... -} - -// Address houses a users address information -type Address struct { - Street string `validate:"required"` - City string `validate:"required"` - Planet string `validate:"required"` - Phone string `validate:"required"` -} - -// use a single instance , it caches struct info -var ( - uni *ut.UniversalTranslator - validate *validator.Validate -) - -func main() { - - // NOTE: ommitting allot of error checking for brevity - - en := en.New() - uni = ut.New(en, en) - - // this is usually know or extracted from http 'Accept-Language' header - // also see uni.FindTranslator(...) - trans, _ := uni.GetTranslator("en") - - validate = validator.New() - en_translations.RegisterDefaultTranslations(validate, trans) - - translateAll(trans) - translateIndividual(trans) - translateOverride(trans) // yep you can specify your own in whatever locale you want! -} - -func translateAll(trans ut.Translator) { - - type User struct { - Username string `validate:"required"` - Tagline string `validate:"required,lt=10"` - Tagline2 string `validate:"required,gt=1"` - } - - user := User{ - Username: "Joeybloggs", - Tagline: "This tagline is way too long.", - Tagline2: "1", - } - - err := validate.Struct(user) - if err != nil { - - // translate all error at once - errs := err.(validator.ValidationErrors) - - // returns a map with key = namespace & value = translated error - // NOTICE: 2 errors are returned and you'll see something surprising - // translations are i18n aware!!!! - // eg. '10 characters' vs '1 character' - fmt.Println(errs.Translate(trans)) - } -} - -func translateIndividual(trans ut.Translator) { - - type User struct { - Username string `validate:"required"` - } - - var user User - - err := validate.Struct(user) - if err != nil { - - errs := err.(validator.ValidationErrors) - - for _, e := range errs { - // can translate each error one at a time. - fmt.Println(e.Translate(trans)) - } - } -} - -func translateOverride(trans ut.Translator) { - - validate.RegisterTranslation("required", trans, func(ut ut.Translator) error { - return ut.Add("required", "{0} must have a value!", true) // see universal-translator for details - }, func(ut ut.Translator, fe validator.FieldError) string { - t, _ := ut.T("required", fe.Field()) - - return t - }) - - type User struct { - Username string `validate:"required"` - } - - var user User - - err := validate.Struct(user) - if err != nil { - - errs := err.(validator.ValidationErrors) - - for _, e := range errs { - // can translate each error one at a time. - fmt.Println(e.Translate(trans)) - } - } -} diff --git a/go-playground/validator/v10/translations/en/en_test.go b/go-playground/validator/v10/translations/en/en_test.go deleted file mode 100644 index 167b1ad..0000000 --- a/go-playground/validator/v10/translations/en/en_test.go +++ /dev/null @@ -1,676 +0,0 @@ -package en - -import ( - "testing" - "time" - - . "git.ningdatech.com/ningda/gin_valid/go-playground/assert/v2" - english "git.ningdatech.com/ningda/gin_valid/go-playground/locales/en" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -func TestTranslations(t *testing.T) { - - eng := english.New() - uni := ut.New(eng, eng) - trans, _ := uni.GetTranslator("en") - - validate := validator.New() - - err := RegisterDefaultTranslations(validate, trans) - Equal(t, err, nil) - - type Inner struct { - EqCSFieldString string - NeCSFieldString string - GtCSFieldString string - GteCSFieldString string - LtCSFieldString string - LteCSFieldString string - } - - type Test struct { - Inner Inner - RequiredString string `validate:"required"` - RequiredNumber int `validate:"required"` - RequiredMultiple []string `validate:"required"` - LenString string `validate:"len=1"` - LenNumber float64 `validate:"len=1113.00"` - LenMultiple []string `validate:"len=7"` - MinString string `validate:"min=1"` - MinNumber float64 `validate:"min=1113.00"` - MinMultiple []string `validate:"min=7"` - MaxString string `validate:"max=3"` - MaxNumber float64 `validate:"max=1113.00"` - MaxMultiple []string `validate:"max=7"` - EqString string `validate:"eq=3"` - EqNumber float64 `validate:"eq=2.33"` - EqMultiple []string `validate:"eq=7"` - NeString string `validate:"ne="` - NeNumber float64 `validate:"ne=0.00"` - NeMultiple []string `validate:"ne=0"` - LtString string `validate:"lt=3"` - LtNumber float64 `validate:"lt=5.56"` - LtMultiple []string `validate:"lt=2"` - LtTime time.Time `validate:"lt"` - LteString string `validate:"lte=3"` - LteNumber float64 `validate:"lte=5.56"` - LteMultiple []string `validate:"lte=2"` - LteTime time.Time `validate:"lte"` - GtString string `validate:"gt=3"` - GtNumber float64 `validate:"gt=5.56"` - GtMultiple []string `validate:"gt=2"` - GtTime time.Time `validate:"gt"` - GteString string `validate:"gte=3"` - GteNumber float64 `validate:"gte=5.56"` - GteMultiple []string `validate:"gte=2"` - GteTime time.Time `validate:"gte"` - EqFieldString string `validate:"eqfield=MaxString"` - EqCSFieldString string `validate:"eqcsfield=Inner.EqCSFieldString"` - NeCSFieldString string `validate:"necsfield=Inner.NeCSFieldString"` - GtCSFieldString string `validate:"gtcsfield=Inner.GtCSFieldString"` - GteCSFieldString string `validate:"gtecsfield=Inner.GteCSFieldString"` - LtCSFieldString string `validate:"ltcsfield=Inner.LtCSFieldString"` - LteCSFieldString string `validate:"ltecsfield=Inner.LteCSFieldString"` - NeFieldString string `validate:"nefield=EqFieldString"` - GtFieldString string `validate:"gtfield=MaxString"` - GteFieldString string `validate:"gtefield=MaxString"` - LtFieldString string `validate:"ltfield=MaxString"` - LteFieldString string `validate:"ltefield=MaxString"` - AlphaString string `validate:"alpha"` - AlphanumString string `validate:"alphanum"` - NumericString string `validate:"numeric"` - NumberString string `validate:"number"` - HexadecimalString string `validate:"hexadecimal"` - HexColorString string `validate:"hexcolor"` - RGBColorString string `validate:"rgb"` - RGBAColorString string `validate:"rgba"` - HSLColorString string `validate:"hsl"` - HSLAColorString string `validate:"hsla"` - Email string `validate:"email"` - URL string `validate:"url"` - URI string `validate:"uri"` - Base64 string `validate:"base64"` - Contains string `validate:"contains=purpose"` - ContainsAny string `validate:"containsany=!@#$"` - Excludes string `validate:"excludes=text"` - ExcludesAll string `validate:"excludesall=!@#$"` - ExcludesRune string `validate:"excludesrune=☻"` - ISBN string `validate:"isbn"` - ISBN10 string `validate:"isbn10"` - ISBN13 string `validate:"isbn13"` - UUID string `validate:"uuid"` - UUID3 string `validate:"uuid3"` - UUID4 string `validate:"uuid4"` - UUID5 string `validate:"uuid5"` - ASCII string `validate:"ascii"` - PrintableASCII string `validate:"printascii"` - MultiByte string `validate:"multibyte"` - DataURI string `validate:"datauri"` - Latitude string `validate:"latitude"` - Longitude string `validate:"longitude"` - SSN string `validate:"ssn"` - IP string `validate:"ip"` - IPv4 string `validate:"ipv4"` - IPv6 string `validate:"ipv6"` - CIDR string `validate:"cidr"` - CIDRv4 string `validate:"cidrv4"` - CIDRv6 string `validate:"cidrv6"` - TCPAddr string `validate:"tcp_addr"` - TCPAddrv4 string `validate:"tcp4_addr"` - TCPAddrv6 string `validate:"tcp6_addr"` - UDPAddr string `validate:"udp_addr"` - UDPAddrv4 string `validate:"udp4_addr"` - UDPAddrv6 string `validate:"udp6_addr"` - IPAddr string `validate:"ip_addr"` - IPAddrv4 string `validate:"ip4_addr"` - IPAddrv6 string `validate:"ip6_addr"` - UinxAddr string `validate:"unix_addr"` // can't fail from within Go's net package currently, but maybe in the future - MAC string `validate:"mac"` - IsColor string `validate:"iscolor"` - StrPtrMinLen *string `validate:"min=10"` - StrPtrMaxLen *string `validate:"max=1"` - StrPtrLen *string `validate:"len=2"` - StrPtrLt *string `validate:"lt=1"` - StrPtrLte *string `validate:"lte=1"` - StrPtrGt *string `validate:"gt=10"` - StrPtrGte *string `validate:"gte=10"` - OneOfString string `validate:"oneof=red green"` - OneOfInt int `validate:"oneof=5 63"` - UniqueSlice []string `validate:"unique"` - UniqueArray [3]string `validate:"unique"` - UniqueMap map[string]string `validate:"unique"` - JSONString string `validate:"json"` - LowercaseString string `validate:"lowercase"` - UppercaseString string `validate:"uppercase"` - Datetime string `validate:"datetime=2006-01-02"` - } - - var test Test - - test.Inner.EqCSFieldString = "1234" - test.Inner.GtCSFieldString = "1234" - test.Inner.GteCSFieldString = "1234" - - test.MaxString = "1234" - test.MaxNumber = 2000 - test.MaxMultiple = make([]string, 9) - - test.LtString = "1234" - test.LtNumber = 6 - test.LtMultiple = make([]string, 3) - test.LtTime = time.Now().Add(time.Hour * 24) - - test.LteString = "1234" - test.LteNumber = 6 - test.LteMultiple = make([]string, 3) - test.LteTime = time.Now().Add(time.Hour * 24) - - test.LtFieldString = "12345" - test.LteFieldString = "12345" - - test.LtCSFieldString = "1234" - test.LteCSFieldString = "1234" - - test.AlphaString = "abc3" - test.AlphanumString = "abc3!" - test.NumericString = "12E.00" - test.NumberString = "12E" - - test.Excludes = "this is some test text" - test.ExcludesAll = "This is Great!" - test.ExcludesRune = "Love it ☻" - - test.ASCII = "カタカナ" - test.PrintableASCII = "カタカナ" - - test.MultiByte = "1234feerf" - - test.LowercaseString = "ABCDEFG" - test.UppercaseString = "abcdefg" - - s := "toolong" - test.StrPtrMaxLen = &s - test.StrPtrLen = &s - - test.UniqueSlice = []string{"1234", "1234"} - test.UniqueMap = map[string]string{"key1": "1234", "key2": "1234"} - test.Datetime = "2008-Feb-01" - - err = validate.Struct(test) - NotEqual(t, err, nil) - - errs, ok := err.(validator.ValidationErrors) - Equal(t, ok, true) - - tests := []struct { - ns string - expected string - }{ - { - ns: "Test.IsColor", - expected: "IsColor must be a valid color", - }, - { - ns: "Test.MAC", - expected: "MAC must contain a valid MAC address", - }, - { - ns: "Test.IPAddr", - expected: "IPAddr must be a resolvable IP address", - }, - { - ns: "Test.IPAddrv4", - expected: "IPAddrv4 must be a resolvable IPv4 address", - }, - { - ns: "Test.IPAddrv6", - expected: "IPAddrv6 must be a resolvable IPv6 address", - }, - { - ns: "Test.UDPAddr", - expected: "UDPAddr must be a valid UDP address", - }, - { - ns: "Test.UDPAddrv4", - expected: "UDPAddrv4 must be a valid IPv4 UDP address", - }, - { - ns: "Test.UDPAddrv6", - expected: "UDPAddrv6 must be a valid IPv6 UDP address", - }, - { - ns: "Test.TCPAddr", - expected: "TCPAddr must be a valid TCP address", - }, - { - ns: "Test.TCPAddrv4", - expected: "TCPAddrv4 must be a valid IPv4 TCP address", - }, - { - ns: "Test.TCPAddrv6", - expected: "TCPAddrv6 must be a valid IPv6 TCP address", - }, - { - ns: "Test.CIDR", - expected: "CIDR must contain a valid CIDR notation", - }, - { - ns: "Test.CIDRv4", - expected: "CIDRv4 must contain a valid CIDR notation for an IPv4 address", - }, - { - ns: "Test.CIDRv6", - expected: "CIDRv6 must contain a valid CIDR notation for an IPv6 address", - }, - { - ns: "Test.SSN", - expected: "SSN must be a valid SSN number", - }, - { - ns: "Test.IP", - expected: "IP must be a valid IP address", - }, - { - ns: "Test.IPv4", - expected: "IPv4 must be a valid IPv4 address", - }, - { - ns: "Test.IPv6", - expected: "IPv6 must be a valid IPv6 address", - }, - { - ns: "Test.DataURI", - expected: "DataURI must contain a valid Data URI", - }, - { - ns: "Test.Latitude", - expected: "Latitude must contain valid latitude coordinates", - }, - { - ns: "Test.Longitude", - expected: "Longitude must contain a valid longitude coordinates", - }, - { - ns: "Test.MultiByte", - expected: "MultiByte must contain multibyte characters", - }, - { - ns: "Test.ASCII", - expected: "ASCII must contain only ascii characters", - }, - { - ns: "Test.PrintableASCII", - expected: "PrintableASCII must contain only printable ascii characters", - }, - { - ns: "Test.UUID", - expected: "UUID must be a valid UUID", - }, - { - ns: "Test.UUID3", - expected: "UUID3 must be a valid version 3 UUID", - }, - { - ns: "Test.UUID4", - expected: "UUID4 must be a valid version 4 UUID", - }, - { - ns: "Test.UUID5", - expected: "UUID5 must be a valid version 5 UUID", - }, - { - ns: "Test.ISBN", - expected: "ISBN must be a valid ISBN number", - }, - { - ns: "Test.ISBN10", - expected: "ISBN10 must be a valid ISBN-10 number", - }, - { - ns: "Test.ISBN13", - expected: "ISBN13 must be a valid ISBN-13 number", - }, - { - ns: "Test.Excludes", - expected: "Excludes cannot contain the text 'text'", - }, - { - ns: "Test.ExcludesAll", - expected: "ExcludesAll cannot contain any of the following characters '!@#$'", - }, - { - ns: "Test.ExcludesRune", - expected: "ExcludesRune cannot contain the following '☻'", - }, - { - ns: "Test.ContainsAny", - expected: "ContainsAny must contain at least one of the following characters '!@#$'", - }, - { - ns: "Test.Contains", - expected: "Contains must contain the text 'purpose'", - }, - { - ns: "Test.Base64", - expected: "Base64 must be a valid Base64 string", - }, - { - ns: "Test.Email", - expected: "Email must be a valid email address", - }, - { - ns: "Test.URL", - expected: "URL must be a valid URL", - }, - { - ns: "Test.URI", - expected: "URI must be a valid URI", - }, - { - ns: "Test.RGBColorString", - expected: "RGBColorString must be a valid RGB color", - }, - { - ns: "Test.RGBAColorString", - expected: "RGBAColorString must be a valid RGBA color", - }, - { - ns: "Test.HSLColorString", - expected: "HSLColorString must be a valid HSL color", - }, - { - ns: "Test.HSLAColorString", - expected: "HSLAColorString must be a valid HSLA color", - }, - { - ns: "Test.HexadecimalString", - expected: "HexadecimalString must be a valid hexadecimal", - }, - { - ns: "Test.HexColorString", - expected: "HexColorString must be a valid HEX color", - }, - { - ns: "Test.NumberString", - expected: "NumberString must be a valid number", - }, - { - ns: "Test.NumericString", - expected: "NumericString must be a valid numeric value", - }, - { - ns: "Test.AlphanumString", - expected: "AlphanumString can only contain alphanumeric characters", - }, - { - ns: "Test.AlphaString", - expected: "AlphaString can only contain alphabetic characters", - }, - { - ns: "Test.LtFieldString", - expected: "LtFieldString must be less than MaxString", - }, - { - ns: "Test.LteFieldString", - expected: "LteFieldString must be less than or equal to MaxString", - }, - { - ns: "Test.GtFieldString", - expected: "GtFieldString must be greater than MaxString", - }, - { - ns: "Test.GteFieldString", - expected: "GteFieldString must be greater than or equal to MaxString", - }, - { - ns: "Test.NeFieldString", - expected: "NeFieldString cannot be equal to EqFieldString", - }, - { - ns: "Test.LtCSFieldString", - expected: "LtCSFieldString must be less than Inner.LtCSFieldString", - }, - { - ns: "Test.LteCSFieldString", - expected: "LteCSFieldString must be less than or equal to Inner.LteCSFieldString", - }, - { - ns: "Test.GtCSFieldString", - expected: "GtCSFieldString must be greater than Inner.GtCSFieldString", - }, - { - ns: "Test.GteCSFieldString", - expected: "GteCSFieldString must be greater than or equal to Inner.GteCSFieldString", - }, - { - ns: "Test.NeCSFieldString", - expected: "NeCSFieldString cannot be equal to Inner.NeCSFieldString", - }, - { - ns: "Test.EqCSFieldString", - expected: "EqCSFieldString must be equal to Inner.EqCSFieldString", - }, - { - ns: "Test.EqFieldString", - expected: "EqFieldString must be equal to MaxString", - }, - { - ns: "Test.GteString", - expected: "GteString must be at least 3 characters in length", - }, - { - ns: "Test.GteNumber", - expected: "GteNumber must be 5.56 or greater", - }, - { - ns: "Test.GteMultiple", - expected: "GteMultiple must contain at least 2 items", - }, - { - ns: "Test.GteTime", - expected: "GteTime must be greater than or equal to the current Date & Time", - }, - { - ns: "Test.GtString", - expected: "GtString must be greater than 3 characters in length", - }, - { - ns: "Test.GtNumber", - expected: "GtNumber must be greater than 5.56", - }, - { - ns: "Test.GtMultiple", - expected: "GtMultiple must contain more than 2 items", - }, - { - ns: "Test.GtTime", - expected: "GtTime must be greater than the current Date & Time", - }, - { - ns: "Test.LteString", - expected: "LteString must be at maximum 3 characters in length", - }, - { - ns: "Test.LteNumber", - expected: "LteNumber must be 5.56 or less", - }, - { - ns: "Test.LteMultiple", - expected: "LteMultiple must contain at maximum 2 items", - }, - { - ns: "Test.LteTime", - expected: "LteTime must be less than or equal to the current Date & Time", - }, - { - ns: "Test.LtString", - expected: "LtString must be less than 3 characters in length", - }, - { - ns: "Test.LtNumber", - expected: "LtNumber must be less than 5.56", - }, - { - ns: "Test.LtMultiple", - expected: "LtMultiple must contain less than 2 items", - }, - { - ns: "Test.LtTime", - expected: "LtTime must be less than the current Date & Time", - }, - { - ns: "Test.NeString", - expected: "NeString should not be equal to ", - }, - { - ns: "Test.NeNumber", - expected: "NeNumber should not be equal to 0.00", - }, - { - ns: "Test.NeMultiple", - expected: "NeMultiple should not be equal to 0", - }, - { - ns: "Test.EqString", - expected: "EqString is not equal to 3", - }, - { - ns: "Test.EqNumber", - expected: "EqNumber is not equal to 2.33", - }, - { - ns: "Test.EqMultiple", - expected: "EqMultiple is not equal to 7", - }, - { - ns: "Test.MaxString", - expected: "MaxString must be a maximum of 3 characters in length", - }, - { - ns: "Test.MaxNumber", - expected: "MaxNumber must be 1,113.00 or less", - }, - { - ns: "Test.MaxMultiple", - expected: "MaxMultiple must contain at maximum 7 items", - }, - { - ns: "Test.MinString", - expected: "MinString must be at least 1 character in length", - }, - { - ns: "Test.MinNumber", - expected: "MinNumber must be 1,113.00 or greater", - }, - { - ns: "Test.MinMultiple", - expected: "MinMultiple must contain at least 7 items", - }, - { - ns: "Test.LenString", - expected: "LenString must be 1 character in length", - }, - { - ns: "Test.LenNumber", - expected: "LenNumber must be equal to 1,113.00", - }, - { - ns: "Test.LenMultiple", - expected: "LenMultiple must contain 7 items", - }, - { - ns: "Test.RequiredString", - expected: "RequiredString is a required field", - }, - { - ns: "Test.RequiredNumber", - expected: "RequiredNumber is a required field", - }, - { - ns: "Test.RequiredMultiple", - expected: "RequiredMultiple is a required field", - }, - { - ns: "Test.StrPtrMinLen", - expected: "StrPtrMinLen must be at least 10 characters in length", - }, - { - ns: "Test.StrPtrMaxLen", - expected: "StrPtrMaxLen must be a maximum of 1 character in length", - }, - { - ns: "Test.StrPtrLen", - expected: "StrPtrLen must be 2 characters in length", - }, - { - ns: "Test.StrPtrLt", - expected: "StrPtrLt must be less than 1 character in length", - }, - { - ns: "Test.StrPtrLte", - expected: "StrPtrLte must be at maximum 1 character in length", - }, - { - ns: "Test.StrPtrGt", - expected: "StrPtrGt must be greater than 10 characters in length", - }, - { - ns: "Test.StrPtrGte", - expected: "StrPtrGte must be at least 10 characters in length", - }, - { - ns: "Test.OneOfString", - expected: "OneOfString must be one of [red green]", - }, - { - ns: "Test.OneOfInt", - expected: "OneOfInt must be one of [5 63]", - }, - { - ns: "Test.UniqueSlice", - expected: "UniqueSlice must contain unique values", - }, - { - ns: "Test.UniqueArray", - expected: "UniqueArray must contain unique values", - }, - { - ns: "Test.UniqueMap", - expected: "UniqueMap must contain unique values", - }, - { - ns: "Test.JSONString", - expected: "JSONString must be a valid json string", - }, - { - ns: "Test.LowercaseString", - expected: "LowercaseString must be a lowercase string", - }, - { - ns: "Test.UppercaseString", - expected: "UppercaseString must be an uppercase string", - }, - { - ns: "Test.Datetime", - expected: "Datetime does not match the 2006-01-02 format", - }, - } - - for _, tt := range tests { - - var fe validator.FieldError - - for _, e := range errs { - if tt.ns == e.Namespace() { - fe = e - break - } - } - - NotEqual(t, fe, nil) - Equal(t, tt.expected, fe.Translate(trans)) - } - -} diff --git a/go-playground/validator/v10/translations/es/es.go b/go-playground/validator/v10/translations/es/es.go deleted file mode 100644 index 8df35ad..0000000 --- a/go-playground/validator/v10/translations/es/es.go +++ /dev/null @@ -1,1375 +0,0 @@ -package es - -import ( - "fmt" - "log" - "reflect" - "strconv" - "strings" - "time" - - "git.ningdatech.com/ningda/gin_valid/go-playground/locales" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -// RegisterDefaultTranslations registers a set of default translations -// for all built in tag's in validator; you may add your own as desired. -func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (err error) { - - translations := []struct { - tag string - translation string - override bool - customRegisFunc validator.RegisterTranslationsFunc - customTransFunc validator.TranslationFunc - }{ - { - tag: "required", - translation: "{0} es un campo requerido", - override: false, - }, - { - tag: "len", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("len-string", "{0} debe tener {1} de longitud", false); err != nil { - return - } - - if err = ut.AddCardinal("len-string-character", "{0} carácter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("len-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("len-number", "{0} debe ser igual a {1}", false); err != nil { - return - } - - if err = ut.Add("len-items", "{0} debe contener {1}", false); err != nil { - return - } - if err = ut.AddCardinal("len-items-item", "{0} elemento", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("len-items-item", "{0} elementos", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("len-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("len-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-items", fe.Field(), c) - - default: - t, err = ut.T("len-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "min", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("min-string", "{0} debe tener al menos {1} de longitud", false); err != nil { - return - } - - if err = ut.AddCardinal("min-string-character", "{0} carácter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("min-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("min-number", "{0} debe ser {1} o más", false); err != nil { - return - } - - if err = ut.Add("min-items", "{0} debe contener al menos {1}", false); err != nil { - return - } - if err = ut.AddCardinal("min-items-item", "{0} elemento", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("min-items-item", "{0} elementos", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("min-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("min-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-items", fe.Field(), c) - - default: - t, err = ut.T("min-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "max", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("max-string", "{0} debe tener un máximo de {1} de longitud", false); err != nil { - return - } - - if err = ut.AddCardinal("max-string-character", "{0} carácter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("max-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("max-number", "{0} debe ser {1} o menos", false); err != nil { - return - } - - if err = ut.Add("max-items", "{0} debe contener como máximo {1}", false); err != nil { - return - } - if err = ut.AddCardinal("max-items-item", "{0} elemento", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("max-items-item", "{0} elementos", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("max-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("max-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-items", fe.Field(), c) - - default: - t, err = ut.T("max-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eq", - translation: "{0} no es igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ne", - translation: "{0} no debería ser igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lt-string", "{0} debe tener menos de {1} de longitud", false); err != nil { - return - } - - if err = ut.AddCardinal("lt-string-character", "{0} carácter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lt-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-number", "{0} debe ser menos de {1}", false); err != nil { - return - } - - if err = ut.Add("lt-items", "{0} debe contener menos de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lt-items-item", "{0} elemento", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lt-items-item", "{0} elementos", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-datetime", "{0} debe ser antes de la fecha y hora actual", false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lte-string", "{0} debe tener un máximo de {1} de longitud", false); err != nil { - return - } - - if err = ut.AddCardinal("lte-string-character", "{0} carácter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lte-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-number", "{0} debe ser {1} o menos", false); err != nil { - return - } - - if err = ut.Add("lte-items", "{0} debe contener como máximo {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lte-items-item", "{0} elemento", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lte-items-item", "{0} elementos", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-datetime", "{0} debe ser antes o durante la fecha y hora actual", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gt-string", "{0} debe ser mayor que {1} en longitud", false); err != nil { - return - } - - if err = ut.AddCardinal("gt-string-character", "{0} carácter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gt-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-number", "{0} debe ser mayor que {1}", false); err != nil { - return - } - - if err = ut.Add("gt-items", "{0} debe contener más de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gt-items-item", "{0} elemento", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gt-items-item", "{0} elementos", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-datetime", "{0} debe ser después de la fecha y hora actual", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gte-string", "{0} debe tener al menos {1} de longitud", false); err != nil { - return - } - - if err = ut.AddCardinal("gte-string-character", "{0} carácter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gte-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-number", "{0} debe ser {1} o mayor", false); err != nil { - return - } - - if err = ut.Add("gte-items", "{0} debe contener al menos {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gte-items-item", "{0} elemento", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gte-items-item", "{0} elementos", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-datetime", "{0} debe ser después o durante la fecha y hora actuales", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqfield", - translation: "{0} debe ser igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqcsfield", - translation: "{0} debe ser igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "necsfield", - translation: "{0} no puede ser igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtcsfield", - translation: "{0} debe ser mayor que {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtecsfield", - translation: "{0} debe ser mayor o igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltcsfield", - translation: "{0} debe ser menor que {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltecsfield", - translation: "{0} debe ser menor o igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "nefield", - translation: "{0} no puede ser igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtfield", - translation: "{0} debe ser mayor que {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtefield", - translation: "{0} debe ser mayor o igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltfield", - translation: "{0} debe ser menor que {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltefield", - translation: "{0} debe ser menor o igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "alpha", - translation: "{0} sólo puede contener caracteres alfabéticos", - override: false, - }, - { - tag: "alphanum", - translation: "{0} sólo puede contener caracteres alfanuméricos", - override: false, - }, - { - tag: "numeric", - translation: "{0} debe ser un valor numérico válido", - override: false, - }, - { - tag: "number", - translation: "{0} debe ser un número válido", - override: false, - }, - { - tag: "hexadecimal", - translation: "{0} debe ser un hexadecimal válido", - override: false, - }, - { - tag: "hexcolor", - translation: "{0} debe ser un color HEX válido", - override: false, - }, - { - tag: "rgb", - translation: "{0} debe ser un color RGB válido", - override: false, - }, - { - tag: "rgba", - translation: "{0} debe ser un color RGBA válido", - override: false, - }, - { - tag: "hsl", - translation: "{0} debe ser un color HSL válido", - override: false, - }, - { - tag: "hsla", - translation: "{0} debe ser un color HSL válido", - override: false, - }, - { - tag: "e164", - translation: "{0} debe ser un número de teléfono válido con formato E.164", - override: false, - }, - { - tag: "email", - translation: "{0} debe ser una dirección de correo electrónico válida", - override: false, - }, - { - tag: "url", - translation: "{0} debe ser un URL válido", - override: false, - }, - { - tag: "uri", - translation: "{0} debe ser una URI válida", - override: false, - }, - { - tag: "base64", - translation: "{0} debe ser una cadena de Base64 válida", - override: false, - }, - { - tag: "contains", - translation: "{0} debe contener el texto '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "containsany", - translation: "{0} debe contener al menos uno de los siguientes caracteres '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludes", - translation: "{0} no puede contener el texto '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesall", - translation: "{0} no puede contener ninguno de los siguientes caracteres '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesrune", - translation: "{0} no puede contener lo siguiente '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "isbn", - translation: "{0} debe ser un número ISBN válido", - override: false, - }, - { - tag: "isbn10", - translation: "{0} debe ser un número ISBN-10 válido", - override: false, - }, - { - tag: "isbn13", - translation: "{0} debe ser un número ISBN-13 válido", - override: false, - }, - { - tag: "uuid", - translation: "{0} debe ser un UUID válido", - override: false, - }, - { - tag: "uuid3", - translation: "{0} debe ser una versión válida 3 UUID", - override: false, - }, - { - tag: "uuid4", - translation: "{0} debe ser una versión válida 4 UUID", - override: false, - }, - { - tag: "uuid5", - translation: "{0} debe ser una versión válida 5 UUID", - override: false, - }, - { - tag: "ascii", - translation: "{0} debe contener sólo caracteres ascii", - override: false, - }, - { - tag: "printascii", - translation: "{0} debe contener sólo caracteres ASCII imprimibles", - override: false, - }, - { - tag: "multibyte", - translation: "{0} debe contener caracteres multibyte", - override: false, - }, - { - tag: "datauri", - translation: "{0} debe contener un URI de datos válido", - override: false, - }, - { - tag: "latitude", - translation: "{0} debe contener coordenadas de latitud válidas", - override: false, - }, - { - tag: "longitude", - translation: "{0} debe contener unas coordenadas de longitud válidas", - override: false, - }, - { - tag: "ssn", - translation: "{0} debe ser un número válido de SSN", - override: false, - }, - { - tag: "ipv4", - translation: "{0} debe ser una dirección IPv4 válida", - override: false, - }, - { - tag: "ipv6", - translation: "{0} debe ser una dirección IPv6 válida", - override: false, - }, - { - tag: "ip", - translation: "{0} debe ser una dirección IP válida", - override: false, - }, - { - tag: "cidr", - translation: "{0} debe contener una anotación válida del CIDR", - override: false, - }, - { - tag: "cidrv4", - translation: "{0} debe contener una notación CIDR válida para una dirección IPv4", - override: false, - }, - { - tag: "cidrv6", - translation: "{0} debe contener una notación CIDR válida para una dirección IPv6", - override: false, - }, - { - tag: "tcp_addr", - translation: "{0} debe ser una dirección TCP válida", - override: false, - }, - { - tag: "tcp4_addr", - translation: "{0} debe ser una dirección IPv4 TCP válida", - override: false, - }, - { - tag: "tcp6_addr", - translation: "{0} debe ser una dirección IPv6 TCP válida", - override: false, - }, - { - tag: "udp_addr", - translation: "{0} debe ser una dirección UDP válida", - override: false, - }, - { - tag: "udp4_addr", - translation: "{0} debe ser una dirección IPv4 UDP válida", - override: false, - }, - { - tag: "udp6_addr", - translation: "{0} debe ser una dirección IPv6 UDP válida", - override: false, - }, - { - tag: "ip_addr", - translation: "{0} debe ser una dirección IP resoluble", - override: false, - }, - { - tag: "ip4_addr", - translation: "{0} debe ser una dirección IPv4 resoluble", - override: false, - }, - { - tag: "ip6_addr", - translation: "{0} debe ser una dirección IPv6 resoluble", - override: false, - }, - { - tag: "unix_addr", - translation: "{0} debe ser una dirección UNIX resoluble", - override: false, - }, - { - tag: "mac", - translation: "{0} debe contener una dirección MAC válida", - override: false, - }, - { - tag: "unique", - translation: "{0} debe contener valores únicos", - override: false, - }, - { - tag: "iscolor", - translation: "{0} debe ser un color válido", - override: false, - }, - { - tag: "oneof", - translation: "{0} debe ser uno de [{1}]", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - s, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - return s - }, - }, - } - - for _, t := range translations { - - if t.customTransFunc != nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, t.customTransFunc) - - } else if t.customTransFunc != nil && t.customRegisFunc == nil { - - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), t.customTransFunc) - - } else if t.customTransFunc == nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, translateFunc) - - } else { - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), translateFunc) - } - - if err != nil { - return - } - } - - return -} - -func registrationFunc(tag string, translation string, override bool) validator.RegisterTranslationsFunc { - - return func(ut ut.Translator) (err error) { - - if err = ut.Add(tag, translation, override); err != nil { - return - } - - return - - } - -} - -func translateFunc(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t -} diff --git a/go-playground/validator/v10/translations/es/es_test.go b/go-playground/validator/v10/translations/es/es_test.go deleted file mode 100644 index 075e263..0000000 --- a/go-playground/validator/v10/translations/es/es_test.go +++ /dev/null @@ -1,652 +0,0 @@ -package es - -import ( - "testing" - "time" - - . "git.ningdatech.com/ningda/gin_valid/go-playground/assert/v2" - spanish "git.ningdatech.com/ningda/gin_valid/go-playground/locales/es" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -func TestTranslations(t *testing.T) { - - spa := spanish.New() - uni := ut.New(spa, spa) - trans, _ := uni.GetTranslator("es") - - validate := validator.New() - - err := RegisterDefaultTranslations(validate, trans) - Equal(t, err, nil) - - type Inner struct { - EqCSFieldString string - NeCSFieldString string - GtCSFieldString string - GteCSFieldString string - LtCSFieldString string - LteCSFieldString string - } - - type Test struct { - Inner Inner - RequiredString string `validate:"required"` - RequiredNumber int `validate:"required"` - RequiredMultiple []string `validate:"required"` - LenString string `validate:"len=1"` - LenNumber float64 `validate:"len=1113.00"` - LenMultiple []string `validate:"len=7"` - MinString string `validate:"min=1"` - MinNumber float64 `validate:"min=1113.00"` - MinMultiple []string `validate:"min=7"` - MaxString string `validate:"max=3"` - MaxNumber float64 `validate:"max=1113.00"` - MaxMultiple []string `validate:"max=7"` - EqString string `validate:"eq=3"` - EqNumber float64 `validate:"eq=2.33"` - EqMultiple []string `validate:"eq=7"` - NeString string `validate:"ne="` - NeNumber float64 `validate:"ne=0.00"` - NeMultiple []string `validate:"ne=0"` - LtString string `validate:"lt=3"` - LtNumber float64 `validate:"lt=5.56"` - LtMultiple []string `validate:"lt=2"` - LtTime time.Time `validate:"lt"` - LteString string `validate:"lte=3"` - LteNumber float64 `validate:"lte=5.56"` - LteMultiple []string `validate:"lte=2"` - LteTime time.Time `validate:"lte"` - GtString string `validate:"gt=3"` - GtNumber float64 `validate:"gt=5.56"` - GtMultiple []string `validate:"gt=2"` - GtTime time.Time `validate:"gt"` - GteString string `validate:"gte=3"` - GteNumber float64 `validate:"gte=5.56"` - GteMultiple []string `validate:"gte=2"` - GteTime time.Time `validate:"gte"` - EqFieldString string `validate:"eqfield=MaxString"` - EqCSFieldString string `validate:"eqcsfield=Inner.EqCSFieldString"` - NeCSFieldString string `validate:"necsfield=Inner.NeCSFieldString"` - GtCSFieldString string `validate:"gtcsfield=Inner.GtCSFieldString"` - GteCSFieldString string `validate:"gtecsfield=Inner.GteCSFieldString"` - LtCSFieldString string `validate:"ltcsfield=Inner.LtCSFieldString"` - LteCSFieldString string `validate:"ltecsfield=Inner.LteCSFieldString"` - NeFieldString string `validate:"nefield=EqFieldString"` - GtFieldString string `validate:"gtfield=MaxString"` - GteFieldString string `validate:"gtefield=MaxString"` - LtFieldString string `validate:"ltfield=MaxString"` - LteFieldString string `validate:"ltefield=MaxString"` - AlphaString string `validate:"alpha"` - AlphanumString string `validate:"alphanum"` - NumericString string `validate:"numeric"` - NumberString string `validate:"number"` - HexadecimalString string `validate:"hexadecimal"` - HexColorString string `validate:"hexcolor"` - RGBColorString string `validate:"rgb"` - RGBAColorString string `validate:"rgba"` - HSLColorString string `validate:"hsl"` - HSLAColorString string `validate:"hsla"` - Email string `validate:"email"` - URL string `validate:"url"` - URI string `validate:"uri"` - Base64 string `validate:"base64"` - Contains string `validate:"contains=purpose"` - ContainsAny string `validate:"containsany=!@#$"` - Excludes string `validate:"excludes=text"` - ExcludesAll string `validate:"excludesall=!@#$"` - ExcludesRune string `validate:"excludesrune=☻"` - ISBN string `validate:"isbn"` - ISBN10 string `validate:"isbn10"` - ISBN13 string `validate:"isbn13"` - UUID string `validate:"uuid"` - UUID3 string `validate:"uuid3"` - UUID4 string `validate:"uuid4"` - UUID5 string `validate:"uuid5"` - ASCII string `validate:"ascii"` - PrintableASCII string `validate:"printascii"` - MultiByte string `validate:"multibyte"` - DataURI string `validate:"datauri"` - Latitude string `validate:"latitude"` - Longitude string `validate:"longitude"` - SSN string `validate:"ssn"` - IP string `validate:"ip"` - IPv4 string `validate:"ipv4"` - IPv6 string `validate:"ipv6"` - CIDR string `validate:"cidr"` - CIDRv4 string `validate:"cidrv4"` - CIDRv6 string `validate:"cidrv6"` - TCPAddr string `validate:"tcp_addr"` - TCPAddrv4 string `validate:"tcp4_addr"` - TCPAddrv6 string `validate:"tcp6_addr"` - UDPAddr string `validate:"udp_addr"` - UDPAddrv4 string `validate:"udp4_addr"` - UDPAddrv6 string `validate:"udp6_addr"` - IPAddr string `validate:"ip_addr"` - IPAddrv4 string `validate:"ip4_addr"` - IPAddrv6 string `validate:"ip6_addr"` - UinxAddr string `validate:"unix_addr"` // can't fail from within Go's net package currently, but maybe in the future - MAC string `validate:"mac"` - IsColor string `validate:"iscolor"` - StrPtrMinLen *string `validate:"min=10"` - StrPtrMaxLen *string `validate:"max=1"` - StrPtrLen *string `validate:"len=2"` - StrPtrLt *string `validate:"lt=1"` - StrPtrLte *string `validate:"lte=1"` - StrPtrGt *string `validate:"gt=10"` - StrPtrGte *string `validate:"gte=10"` - OneOfString string `validate:"oneof=red green"` - OneOfInt int `validate:"oneof=5 63"` - UniqueSlice []string `validate:"unique"` - UniqueArray [3]string `validate:"unique"` - UniqueMap map[string]string `validate:"unique"` - } - - var test Test - - test.Inner.EqCSFieldString = "1234" - test.Inner.GtCSFieldString = "1234" - test.Inner.GteCSFieldString = "1234" - - test.MaxString = "1234" - test.MaxNumber = 2000 - test.MaxMultiple = make([]string, 9) - - test.LtString = "1234" - test.LtNumber = 6 - test.LtMultiple = make([]string, 3) - test.LtTime = time.Now().Add(time.Hour * 24) - - test.LteString = "1234" - test.LteNumber = 6 - test.LteMultiple = make([]string, 3) - test.LteTime = time.Now().Add(time.Hour * 24) - - test.LtFieldString = "12345" - test.LteFieldString = "12345" - - test.LtCSFieldString = "1234" - test.LteCSFieldString = "1234" - - test.AlphaString = "abc3" - test.AlphanumString = "abc3!" - test.NumericString = "12E.00" - test.NumberString = "12E" - - test.Excludes = "this is some test text" - test.ExcludesAll = "This is Great!" - test.ExcludesRune = "Love it ☻" - - test.ASCII = "カタカナ" - test.PrintableASCII = "カタカナ" - - test.MultiByte = "1234feerf" - - s := "toolong" - test.StrPtrMaxLen = &s - test.StrPtrLen = &s - - test.UniqueSlice = []string{"1234", "1234"} - test.UniqueMap = map[string]string{"key1": "1234", "key2": "1234"} - - err = validate.Struct(test) - NotEqual(t, err, nil) - - errs, ok := err.(validator.ValidationErrors) - Equal(t, ok, true) - - tests := []struct { - ns string - expected string - }{ - { - ns: "Test.IsColor", - expected: "IsColor debe ser un color válido", - }, - { - ns: "Test.MAC", - expected: "MAC debe contener una dirección MAC válida", - }, - { - ns: "Test.IPAddr", - expected: "IPAddr debe ser una dirección IP resoluble", - }, - { - ns: "Test.IPAddrv4", - expected: "IPAddrv4 debe ser una dirección IPv4 resoluble", - }, - { - ns: "Test.IPAddrv6", - expected: "IPAddrv6 debe ser una dirección IPv6 resoluble", - }, - { - ns: "Test.UDPAddr", - expected: "UDPAddr debe ser una dirección UDP válida", - }, - { - ns: "Test.UDPAddrv4", - expected: "UDPAddrv4 debe ser una dirección IPv4 UDP válida", - }, - { - ns: "Test.UDPAddrv6", - expected: "UDPAddrv6 debe ser una dirección IPv6 UDP válida", - }, - { - ns: "Test.TCPAddr", - expected: "TCPAddr debe ser una dirección TCP válida", - }, - { - ns: "Test.TCPAddrv4", - expected: "TCPAddrv4 debe ser una dirección IPv4 TCP válida", - }, - { - ns: "Test.TCPAddrv6", - expected: "TCPAddrv6 debe ser una dirección IPv6 TCP válida", - }, - { - ns: "Test.CIDR", - expected: "CIDR debe contener una anotación válida del CIDR", - }, - { - ns: "Test.CIDRv4", - expected: "CIDRv4 debe contener una notación CIDR válida para una dirección IPv4", - }, - { - ns: "Test.CIDRv6", - expected: "CIDRv6 debe contener una notación CIDR válida para una dirección IPv6", - }, - { - ns: "Test.SSN", - expected: "SSN debe ser un número válido de SSN", - }, - { - ns: "Test.IP", - expected: "IP debe ser una dirección IP válida", - }, - { - ns: "Test.IPv4", - expected: "IPv4 debe ser una dirección IPv4 válida", - }, - { - ns: "Test.IPv6", - expected: "IPv6 debe ser una dirección IPv6 válida", - }, - { - ns: "Test.DataURI", - expected: "DataURI debe contener un URI de datos válido", - }, - { - ns: "Test.Latitude", - expected: "Latitude debe contener coordenadas de latitud válidas", - }, - { - ns: "Test.Longitude", - expected: "Longitude debe contener unas coordenadas de longitud válidas", - }, - { - ns: "Test.MultiByte", - expected: "MultiByte debe contener caracteres multibyte", - }, - { - ns: "Test.ASCII", - expected: "ASCII debe contener sólo caracteres ascii", - }, - { - ns: "Test.PrintableASCII", - expected: "PrintableASCII debe contener sólo caracteres ASCII imprimibles", - }, - { - ns: "Test.UUID", - expected: "UUID debe ser un UUID válido", - }, - { - ns: "Test.UUID3", - expected: "UUID3 debe ser una versión válida 3 UUID", - }, - { - ns: "Test.UUID4", - expected: "UUID4 debe ser una versión válida 4 UUID", - }, - { - ns: "Test.UUID5", - expected: "UUID5 debe ser una versión válida 5 UUID", - }, - { - ns: "Test.ISBN", - expected: "ISBN debe ser un número ISBN válido", - }, - { - ns: "Test.ISBN10", - expected: "ISBN10 debe ser un número ISBN-10 válido", - }, - { - ns: "Test.ISBN13", - expected: "ISBN13 debe ser un número ISBN-13 válido", - }, - { - ns: "Test.Excludes", - expected: "Excludes no puede contener el texto 'text'", - }, - { - ns: "Test.ExcludesAll", - expected: "ExcludesAll no puede contener ninguno de los siguientes caracteres '!@#$'", - }, - { - ns: "Test.ExcludesRune", - expected: "ExcludesRune no puede contener lo siguiente '☻'", - }, - { - ns: "Test.ContainsAny", - expected: "ContainsAny debe contener al menos uno de los siguientes caracteres '!@#$'", - }, - { - ns: "Test.Contains", - expected: "Contains debe contener el texto 'purpose'", - }, - { - ns: "Test.Base64", - expected: "Base64 debe ser una cadena de Base64 válida", - }, - { - ns: "Test.Email", - expected: "Email debe ser una dirección de correo electrónico válida", - }, - { - ns: "Test.URL", - expected: "URL debe ser un URL válido", - }, - { - ns: "Test.URI", - expected: "URI debe ser una URI válida", - }, - { - ns: "Test.RGBColorString", - expected: "RGBColorString debe ser un color RGB válido", - }, - { - ns: "Test.RGBAColorString", - expected: "RGBAColorString debe ser un color RGBA válido", - }, - { - ns: "Test.HSLColorString", - expected: "HSLColorString debe ser un color HSL válido", - }, - { - ns: "Test.HSLAColorString", - expected: "HSLAColorString debe ser un color HSL válido", - }, - { - ns: "Test.HexadecimalString", - expected: "HexadecimalString debe ser un hexadecimal válido", - }, - { - ns: "Test.HexColorString", - expected: "HexColorString debe ser un color HEX válido", - }, - { - ns: "Test.NumberString", - expected: "NumberString debe ser un número válido", - }, - { - ns: "Test.NumericString", - expected: "NumericString debe ser un valor numérico válido", - }, - { - ns: "Test.AlphanumString", - expected: "AlphanumString sólo puede contener caracteres alfanuméricos", - }, - { - ns: "Test.AlphaString", - expected: "AlphaString sólo puede contener caracteres alfabéticos", - }, - { - ns: "Test.LtFieldString", - expected: "LtFieldString debe ser menor que MaxString", - }, - { - ns: "Test.LteFieldString", - expected: "LteFieldString debe ser menor o igual a MaxString", - }, - { - ns: "Test.GtFieldString", - expected: "GtFieldString debe ser mayor que MaxString", - }, - { - ns: "Test.GteFieldString", - expected: "GteFieldString debe ser mayor o igual a MaxString", - }, - { - ns: "Test.NeFieldString", - expected: "NeFieldString no puede ser igual a EqFieldString", - }, - { - ns: "Test.LtCSFieldString", - expected: "LtCSFieldString debe ser menor que Inner.LtCSFieldString", - }, - { - ns: "Test.LteCSFieldString", - expected: "LteCSFieldString debe ser menor o igual a Inner.LteCSFieldString", - }, - { - ns: "Test.GtCSFieldString", - expected: "GtCSFieldString debe ser mayor que Inner.GtCSFieldString", - }, - { - ns: "Test.GteCSFieldString", - expected: "GteCSFieldString debe ser mayor o igual a Inner.GteCSFieldString", - }, - { - ns: "Test.NeCSFieldString", - expected: "NeCSFieldString no puede ser igual a Inner.NeCSFieldString", - }, - { - ns: "Test.EqCSFieldString", - expected: "EqCSFieldString debe ser igual a Inner.EqCSFieldString", - }, - { - ns: "Test.EqFieldString", - expected: "EqFieldString debe ser igual a MaxString", - }, - { - ns: "Test.GteString", - expected: "GteString debe tener al menos 3 caracteres de longitud", - }, - { - ns: "Test.GteNumber", - expected: "GteNumber debe ser 5,56 o mayor", - }, - { - ns: "Test.GteMultiple", - expected: "GteMultiple debe contener al menos 2 elementos", - }, - { - ns: "Test.GteTime", - expected: "GteTime debe ser después o durante la fecha y hora actuales", - }, - { - ns: "Test.GtString", - expected: "GtString debe ser mayor que 3 caracteres en longitud", - }, - { - ns: "Test.GtNumber", - expected: "GtNumber debe ser mayor que 5,56", - }, - { - ns: "Test.GtMultiple", - expected: "GtMultiple debe contener más de 2 elementos", - }, - { - ns: "Test.GtTime", - expected: "GtTime debe ser después de la fecha y hora actual", - }, - { - ns: "Test.LteString", - expected: "LteString debe tener un máximo de 3 caracteres de longitud", - }, - { - ns: "Test.LteNumber", - expected: "LteNumber debe ser 5,56 o menos", - }, - { - ns: "Test.LteMultiple", - expected: "LteMultiple debe contener como máximo 2 elementos", - }, - { - ns: "Test.LteTime", - expected: "LteTime debe ser antes o durante la fecha y hora actual", - }, - { - ns: "Test.LtString", - expected: "LtString debe tener menos de 3 caracteres de longitud", - }, - { - ns: "Test.LtNumber", - expected: "LtNumber debe ser menos de 5,56", - }, - { - ns: "Test.LtMultiple", - expected: "LtMultiple debe contener menos de 2 elementos", - }, - { - ns: "Test.LtTime", - expected: "LtTime debe ser antes de la fecha y hora actual", - }, - { - ns: "Test.NeString", - expected: "NeString no debería ser igual a ", - }, - { - ns: "Test.NeNumber", - expected: "NeNumber no debería ser igual a 0.00", - }, - { - ns: "Test.NeMultiple", - expected: "NeMultiple no debería ser igual a 0", - }, - { - ns: "Test.EqString", - expected: "EqString no es igual a 3", - }, - { - ns: "Test.EqNumber", - expected: "EqNumber no es igual a 2.33", - }, - { - ns: "Test.EqMultiple", - expected: "EqMultiple no es igual a 7", - }, - { - ns: "Test.MaxString", - expected: "MaxString debe tener un máximo de 3 caracteres de longitud", - }, - { - ns: "Test.MaxNumber", - expected: "MaxNumber debe ser 1.113,00 o menos", - }, - { - ns: "Test.MaxMultiple", - expected: "MaxMultiple debe contener como máximo 7 elementos", - }, - { - ns: "Test.MinString", - expected: "MinString debe tener al menos 1 carácter de longitud", - }, - { - ns: "Test.MinNumber", - expected: "MinNumber debe ser 1.113,00 o más", - }, - { - ns: "Test.MinMultiple", - expected: "MinMultiple debe contener al menos 7 elementos", - }, - { - ns: "Test.LenString", - expected: "LenString debe tener 1 carácter de longitud", - }, - { - ns: "Test.LenNumber", - expected: "LenNumber debe ser igual a 1.113,00", - }, - { - ns: "Test.LenMultiple", - expected: "LenMultiple debe contener 7 elementos", - }, - { - ns: "Test.RequiredString", - expected: "RequiredString es un campo requerido", - }, - { - ns: "Test.RequiredNumber", - expected: "RequiredNumber es un campo requerido", - }, - { - ns: "Test.RequiredMultiple", - expected: "RequiredMultiple es un campo requerido", - }, - { - ns: "Test.StrPtrMinLen", - expected: "StrPtrMinLen debe tener al menos 10 caracteres de longitud", - }, - { - ns: "Test.StrPtrMaxLen", - expected: "StrPtrMaxLen debe tener un máximo de 1 carácter de longitud", - }, - { - ns: "Test.StrPtrLen", - expected: "StrPtrLen debe tener 2 caracteres de longitud", - }, - { - ns: "Test.StrPtrLt", - expected: "StrPtrLt debe tener menos de 1 carácter de longitud", - }, - { - ns: "Test.StrPtrLte", - expected: "StrPtrLte debe tener un máximo de 1 carácter de longitud", - }, - { - ns: "Test.StrPtrGt", - expected: "StrPtrGt debe ser mayor que 10 caracteres en longitud", - }, - { - ns: "Test.StrPtrGte", - expected: "StrPtrGte debe tener al menos 10 caracteres de longitud", - }, - { - ns: "Test.OneOfString", - expected: "OneOfString debe ser uno de [red green]", - }, - { - ns: "Test.OneOfInt", - expected: "OneOfInt debe ser uno de [5 63]", - }, - { - ns: "Test.UniqueSlice", - expected: "UniqueSlice debe contener valores únicos", - }, - { - ns: "Test.UniqueArray", - expected: "UniqueArray debe contener valores únicos", - }, - { - ns: "Test.UniqueMap", - expected: "UniqueMap debe contener valores únicos", - }, - } - - for _, tt := range tests { - - var fe validator.FieldError - - for _, e := range errs { - if tt.ns == e.Namespace() { - fe = e - break - } - } - - NotEqual(t, fe, nil) - Equal(t, tt.expected, fe.Translate(trans)) - } - -} diff --git a/go-playground/validator/v10/translations/fr/fr.go b/go-playground/validator/v10/translations/fr/fr.go deleted file mode 100644 index b27c588..0000000 --- a/go-playground/validator/v10/translations/fr/fr.go +++ /dev/null @@ -1,1365 +0,0 @@ -package fr - -import ( - "fmt" - "log" - "reflect" - "strconv" - "strings" - "time" - - "git.ningdatech.com/ningda/gin_valid/go-playground/locales" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -// RegisterDefaultTranslations registers a set of default translations -// for all built in tag's in validator; you may add your own as desired. -func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (err error) { - - translations := []struct { - tag string - translation string - override bool - customRegisFunc validator.RegisterTranslationsFunc - customTransFunc validator.TranslationFunc - }{ - { - tag: "required", - translation: "{0} est un champ obligatoire", - override: false, - }, - { - tag: "len", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("len-string", "{0} doit faire une taille de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("len-string-character", "{0} caractère", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("len-string-character", "{0} caractères", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("len-number", "{0} doit être égal à {1}", false); err != nil { - return - } - - if err = ut.Add("len-elements", "{0} doit contenir {1}", false); err != nil { - return - } - if err = ut.AddCardinal("len-elements-element", "{0} element", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("len-elements-element", "{0} elements", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("len-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("len-elements-element", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-elements", fe.Field(), c) - - default: - t, err = ut.T("len-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "min", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("min-string", "{0} doit faire une taille minimum de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("min-string-character", "{0} caractère", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("min-string-character", "{0} caractères", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("min-number", "{0} doit être égal à {1} ou plus", false); err != nil { - return - } - - if err = ut.Add("min-elements", "{0} doit contenir au moins {1}", false); err != nil { - return - } - if err = ut.AddCardinal("min-elements-element", "{0} element", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("min-elements-element", "{0} elements", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("min-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("min-elements-element", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-elements", fe.Field(), c) - - default: - t, err = ut.T("min-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "max", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("max-string", "{0} doit faire une taille maximum de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("max-string-character", "{0} caractère", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("max-string-character", "{0} caractères", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("max-number", "{0} doit être égal à {1} ou moins", false); err != nil { - return - } - - if err = ut.Add("max-elements", "{0} doit contenir au maximum {1}", false); err != nil { - return - } - if err = ut.AddCardinal("max-elements-element", "{0} element", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("max-elements-element", "{0} elements", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("max-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("max-elements-element", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-elements", fe.Field(), c) - - default: - t, err = ut.T("max-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eq", - translation: "{0} n'est pas égal à {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ne", - translation: "{0} ne doit pas être égal à {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lt-string", "{0} doit avoir une taille inférieure à {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lt-string-character", "{0} caractère", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lt-string-character", "{0} caractères", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-number", "{0} doit être inférieur à {1}", false); err != nil { - return - } - - if err = ut.Add("lt-elements", "{0} doit contenir mois de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lt-elements-element", "{0} element", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lt-elements-element", "{0} elements", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-datetime", "{0} doit être avant la date et l'heure actuelle", false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-elements-element", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-elements", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lte-string", "{0} doit faire une taille maximum de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lte-string-character", "{0} caractère", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lte-string-character", "{0} caractères", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-number", "{0} doit faire {1} ou moins", false); err != nil { - return - } - - if err = ut.Add("lte-elements", "{0} doit contenir un maximum de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lte-elements-element", "{0} element", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lte-elements-element", "{0} elements", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-datetime", "{0} doit être avant ou pendant la date et l'heure actuelle", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-elements-element", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-elements", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gt-string", "{0} doit avoir une taille supérieur à {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gt-string-character", "{0} caractère", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gt-string-character", "{0} caractères", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-number", "{0} doit être supérieur à {1}", false); err != nil { - return - } - - if err = ut.Add("gt-elements", "{0} doit contenir plus de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gt-elements-element", "{0} element", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gt-elements-element", "{0} elements", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-datetime", "{0} doit être après la date et l'heure actuelle", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-elements-element", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-elements", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gte-string", "{0} doit faire une taille d'au moins {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gte-string-character", "{0} caractère", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gte-string-character", "{0} caractères", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-number", "{0} doit être {1} ou plus", false); err != nil { - return - } - - if err = ut.Add("gte-elements", "{0} doit contenir au moins {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gte-elements-element", "{0} element", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gte-elements-element", "{0} elements", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-datetime", "{0} doit être après ou pendant la date et l'heure actuelle", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-elements-element", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-elements", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqfield", - translation: "{0} doit être égal à {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqcsfield", - translation: "{0} doit être égal à {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "necsfield", - translation: "{0} ne doit pas être égal à {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtcsfield", - translation: "{0} doit être supérieur à {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtecsfield", - translation: "{0} doit être supérieur ou égal à {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltcsfield", - translation: "{0} doit être inférieur à {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltecsfield", - translation: "{0} doit être inférieur ou égal à {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "nefield", - translation: "{0} ne doit pas être égal à {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtfield", - translation: "{0} doit être supérieur à {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtefield", - translation: "{0} doit être supérieur ou égal à {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltfield", - translation: "{0} doit être inférieur à {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltefield", - translation: "{0} doit être inférieur ou égal à {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "alpha", - translation: "{0} ne doit contenir que des caractères alphabétiques", - override: false, - }, - { - tag: "alphanum", - translation: "{0} ne doit contenir que des caractères alphanumériques", - override: false, - }, - { - tag: "numeric", - translation: "{0} doit être une valeur numérique valide", - override: false, - }, - { - tag: "number", - translation: "{0} doit être un nombre valid", - override: false, - }, - { - tag: "hexadecimal", - translation: "{0} doit être une chaîne de caractères au format hexadécimal valide", - override: false, - }, - { - tag: "hexcolor", - translation: "{0} doit être une couleur au format HEX valide", - override: false, - }, - { - tag: "rgb", - translation: "{0} doit être une couleur au format RGB valide", - override: false, - }, - { - tag: "rgba", - translation: "{0} doit être une couleur au format RGBA valide", - override: false, - }, - { - tag: "hsl", - translation: "{0} doit être une couleur au format HSL valide", - override: false, - }, - { - tag: "hsla", - translation: "{0} doit être une couleur au format HSLA valide", - override: false, - }, - { - tag: "email", - translation: "{0} doit être une adresse email valide", - override: false, - }, - { - tag: "url", - translation: "{0} doit être une URL valide", - override: false, - }, - { - tag: "uri", - translation: "{0} doit être une URI valide", - override: false, - }, - { - tag: "base64", - translation: "{0} doit être une chaîne de caractères au format Base64 valide", - override: false, - }, - { - tag: "contains", - translation: "{0} doit contenir le texte '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "containsany", - translation: "{0} doit contenir au moins l' un des caractères suivants '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludes", - translation: "{0} ne doit pas contenir le texte '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesall", - translation: "{0} ne doit pas contenir l'un des caractères suivants '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesrune", - translation: "{0} ne doit pas contenir ce qui suit '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "isbn", - translation: "{0} doit être un numéro ISBN valid", - override: false, - }, - { - tag: "isbn10", - translation: "{0} doit être un numéro ISBN-10 valid", - override: false, - }, - { - tag: "isbn13", - translation: "{0} doit être un numéro ISBN-13 valid", - override: false, - }, - { - tag: "uuid", - translation: "{0} doit être un UUID valid", - override: false, - }, - { - tag: "uuid3", - translation: "{0} doit être un UUID version 3 valid", - override: false, - }, - { - tag: "uuid4", - translation: "{0} doit être un UUID version 4 valid", - override: false, - }, - { - tag: "uuid5", - translation: "{0} doit être un UUID version 5 valid", - override: false, - }, - { - tag: "ascii", - translation: "{0} ne doit contenir que des caractères ascii", - override: false, - }, - { - tag: "printascii", - translation: "{0} ne doit contenir que des caractères ascii affichables", - override: false, - }, - { - tag: "multibyte", - translation: "{0} doit contenir des caractères multioctets", - override: false, - }, - { - tag: "datauri", - translation: "{0} doit contenir une URI data valide", - override: false, - }, - { - tag: "latitude", - translation: "{0} doit contenir des coordonnées latitude valides", - override: false, - }, - { - tag: "longitude", - translation: "{0} doit contenir des coordonnées longitudes valides", - override: false, - }, - { - tag: "ssn", - translation: "{0} doit être un numéro SSN valide", - override: false, - }, - { - tag: "ipv4", - translation: "{0} doit être une adressse IPv4 valide", - override: false, - }, - { - tag: "ipv6", - translation: "{0} doit être une adressse IPv6 valide", - override: false, - }, - { - tag: "ip", - translation: "{0} doit être une adressse IP valide", - override: false, - }, - { - tag: "cidr", - translation: "{0} doit contenir une notation CIDR valide", - override: false, - }, - { - tag: "cidrv4", - translation: "{0} doit contenir une notation CIDR valide pour une adresse IPv4", - override: false, - }, - { - tag: "cidrv6", - translation: "{0} doit contenir une notation CIDR valide pour une adresse IPv6", - override: false, - }, - { - tag: "tcp_addr", - translation: "{0} doit être une adressse TCP valide", - override: false, - }, - { - tag: "tcp4_addr", - translation: "{0} doit être une adressse IPv4 TCP valide", - override: false, - }, - { - tag: "tcp6_addr", - translation: "{0} doit être une adressse IPv6 TCP valide", - override: false, - }, - { - tag: "udp_addr", - translation: "{0} doit être une adressse UDP valide", - override: false, - }, - { - tag: "udp4_addr", - translation: "{0} doit être une adressse IPv4 UDP valide", - override: false, - }, - { - tag: "udp6_addr", - translation: "{0} doit être une adressse IPv6 UDP valide", - override: false, - }, - { - tag: "ip_addr", - translation: "{0} doit être une adresse IP résolvable", - override: false, - }, - { - tag: "ip4_addr", - translation: "{0} doit être une adresse IPv4 résolvable", - override: false, - }, - { - tag: "ip6_addr", - translation: "{0} doit être une adresse IPv6 résolvable", - override: false, - }, - { - tag: "unix_addr", - translation: "{0} doit être une adresse UNIX résolvable", - override: false, - }, - { - tag: "mac", - translation: "{0} doit contenir une adresse MAC valide", - override: false, - }, - { - tag: "iscolor", - translation: "{0} doit être une couleur valide", - override: false, - }, - { - tag: "oneof", - translation: "{0} doit être l'un des choix suivants [{1}]", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - s, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - return s - }, - }, - } - - for _, t := range translations { - - if t.customTransFunc != nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, t.customTransFunc) - - } else if t.customTransFunc != nil && t.customRegisFunc == nil { - - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), t.customTransFunc) - - } else if t.customTransFunc == nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, translateFunc) - - } else { - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), translateFunc) - } - - if err != nil { - return - } - } - - return -} - -func registrationFunc(tag string, translation string, override bool) validator.RegisterTranslationsFunc { - - return func(ut ut.Translator) (err error) { - - if err = ut.Add(tag, translation, override); err != nil { - return - } - - return - - } - -} - -func translateFunc(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t -} diff --git a/go-playground/validator/v10/translations/fr/fr_test.go b/go-playground/validator/v10/translations/fr/fr_test.go deleted file mode 100644 index a9b76ba..0000000 --- a/go-playground/validator/v10/translations/fr/fr_test.go +++ /dev/null @@ -1,634 +0,0 @@ -package fr - -import ( - "testing" - "time" - - . "git.ningdatech.com/ningda/gin_valid/go-playground/assert/v2" - french "git.ningdatech.com/ningda/gin_valid/go-playground/locales/fr" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -func TestTranslations(t *testing.T) { - - fre := french.New() - uni := ut.New(fre, fre) - trans, _ := uni.GetTranslator("fr") - - validate := validator.New() - - err := RegisterDefaultTranslations(validate, trans) - Equal(t, err, nil) - - type Inner struct { - EqCSFieldString string - NeCSFieldString string - GtCSFieldString string - GteCSFieldString string - LtCSFieldString string - LteCSFieldString string - } - - type Test struct { - Inner Inner - RequiredString string `validate:"required"` - RequiredNumber int `validate:"required"` - RequiredMultiple []string `validate:"required"` - LenString string `validate:"len=1"` - LenNumber float64 `validate:"len=1113.00"` - LenMultiple []string `validate:"len=7"` - MinString string `validate:"min=1"` - MinNumber float64 `validate:"min=1113.00"` - MinMultiple []string `validate:"min=7"` - MaxString string `validate:"max=3"` - MaxNumber float64 `validate:"max=1113.00"` - MaxMultiple []string `validate:"max=7"` - EqString string `validate:"eq=3"` - EqNumber float64 `validate:"eq=2.33"` - EqMultiple []string `validate:"eq=7"` - NeString string `validate:"ne="` - NeNumber float64 `validate:"ne=0.00"` - NeMultiple []string `validate:"ne=0"` - LtString string `validate:"lt=3"` - LtNumber float64 `validate:"lt=5.56"` - LtMultiple []string `validate:"lt=2"` - LtTime time.Time `validate:"lt"` - LteString string `validate:"lte=3"` - LteNumber float64 `validate:"lte=5.56"` - LteMultiple []string `validate:"lte=2"` - LteTime time.Time `validate:"lte"` - GtString string `validate:"gt=3"` - GtNumber float64 `validate:"gt=5.56"` - GtMultiple []string `validate:"gt=2"` - GtTime time.Time `validate:"gt"` - GteString string `validate:"gte=3"` - GteNumber float64 `validate:"gte=5.56"` - GteMultiple []string `validate:"gte=2"` - GteTime time.Time `validate:"gte"` - EqFieldString string `validate:"eqfield=MaxString"` - EqCSFieldString string `validate:"eqcsfield=Inner.EqCSFieldString"` - NeCSFieldString string `validate:"necsfield=Inner.NeCSFieldString"` - GtCSFieldString string `validate:"gtcsfield=Inner.GtCSFieldString"` - GteCSFieldString string `validate:"gtecsfield=Inner.GteCSFieldString"` - LtCSFieldString string `validate:"ltcsfield=Inner.LtCSFieldString"` - LteCSFieldString string `validate:"ltecsfield=Inner.LteCSFieldString"` - NeFieldString string `validate:"nefield=EqFieldString"` - GtFieldString string `validate:"gtfield=MaxString"` - GteFieldString string `validate:"gtefield=MaxString"` - LtFieldString string `validate:"ltfield=MaxString"` - LteFieldString string `validate:"ltefield=MaxString"` - AlphaString string `validate:"alpha"` - AlphanumString string `validate:"alphanum"` - NumericString string `validate:"numeric"` - NumberString string `validate:"number"` - HexadecimalString string `validate:"hexadecimal"` - HexColorString string `validate:"hexcolor"` - RGBColorString string `validate:"rgb"` - RGBAColorString string `validate:"rgba"` - HSLColorString string `validate:"hsl"` - HSLAColorString string `validate:"hsla"` - Email string `validate:"email"` - URL string `validate:"url"` - URI string `validate:"uri"` - Base64 string `validate:"base64"` - Contains string `validate:"contains=purpose"` - ContainsAny string `validate:"containsany=!@#$"` - Excludes string `validate:"excludes=text"` - ExcludesAll string `validate:"excludesall=!@#$"` - ExcludesRune string `validate:"excludesrune=☻"` - ISBN string `validate:"isbn"` - ISBN10 string `validate:"isbn10"` - ISBN13 string `validate:"isbn13"` - UUID string `validate:"uuid"` - UUID3 string `validate:"uuid3"` - UUID4 string `validate:"uuid4"` - UUID5 string `validate:"uuid5"` - ASCII string `validate:"ascii"` - PrintableASCII string `validate:"printascii"` - MultiByte string `validate:"multibyte"` - DataURI string `validate:"datauri"` - Latitude string `validate:"latitude"` - Longitude string `validate:"longitude"` - SSN string `validate:"ssn"` - IP string `validate:"ip"` - IPv4 string `validate:"ipv4"` - IPv6 string `validate:"ipv6"` - CIDR string `validate:"cidr"` - CIDRv4 string `validate:"cidrv4"` - CIDRv6 string `validate:"cidrv6"` - TCPAddr string `validate:"tcp_addr"` - TCPAddrv4 string `validate:"tcp4_addr"` - TCPAddrv6 string `validate:"tcp6_addr"` - UDPAddr string `validate:"udp_addr"` - UDPAddrv4 string `validate:"udp4_addr"` - UDPAddrv6 string `validate:"udp6_addr"` - IPAddr string `validate:"ip_addr"` - IPAddrv4 string `validate:"ip4_addr"` - IPAddrv6 string `validate:"ip6_addr"` - UinxAddr string `validate:"unix_addr"` // can't fail from within Go's net package currently, but maybe in the future - MAC string `validate:"mac"` - IsColor string `validate:"iscolor"` - StrPtrMinLen *string `validate:"min=10"` - StrPtrMaxLen *string `validate:"max=1"` - StrPtrLen *string `validate:"len=2"` - StrPtrLt *string `validate:"lt=1"` - StrPtrLte *string `validate:"lte=1"` - StrPtrGt *string `validate:"gt=10"` - StrPtrGte *string `validate:"gte=10"` - OneOfString string `validate:"oneof=red green"` - OneOfInt int `validate:"oneof=5 63"` - } - - var test Test - - test.Inner.EqCSFieldString = "1234" - test.Inner.GtCSFieldString = "1234" - test.Inner.GteCSFieldString = "1234" - - test.MaxString = "1234" - test.MaxNumber = 2000 - test.MaxMultiple = make([]string, 9) - - test.LtString = "1234" - test.LtNumber = 6 - test.LtMultiple = make([]string, 3) - test.LtTime = time.Now().Add(time.Hour * 24) - - test.LteString = "1234" - test.LteNumber = 6 - test.LteMultiple = make([]string, 3) - test.LteTime = time.Now().Add(time.Hour * 24) - - test.LtFieldString = "12345" - test.LteFieldString = "12345" - - test.LtCSFieldString = "1234" - test.LteCSFieldString = "1234" - - test.AlphaString = "abc3" - test.AlphanumString = "abc3!" - test.NumericString = "12E.00" - test.NumberString = "12E" - - test.Excludes = "this is some test text" - test.ExcludesAll = "This is Great!" - test.ExcludesRune = "Love it ☻" - - test.ASCII = "カタカナ" - test.PrintableASCII = "カタカナ" - - test.MultiByte = "1234feerf" - - s := "toolong" - test.StrPtrMaxLen = &s - test.StrPtrLen = &s - - err = validate.Struct(test) - NotEqual(t, err, nil) - - errs, ok := err.(validator.ValidationErrors) - Equal(t, ok, true) - - tests := []struct { - ns string - expected string - }{ - { - ns: "Test.IsColor", - expected: "IsColor doit être une couleur valide", - }, - { - ns: "Test.MAC", - expected: "MAC doit contenir une adresse MAC valide", - }, - { - ns: "Test.IPAddr", - expected: "IPAddr doit être une adresse IP résolvable", - }, - { - ns: "Test.IPAddrv4", - expected: "IPAddrv4 doit être une adresse IPv4 résolvable", - }, - { - ns: "Test.IPAddrv6", - expected: "IPAddrv6 doit être une adresse IPv6 résolvable", - }, - { - ns: "Test.UDPAddr", - expected: "UDPAddr doit être une adressse UDP valide", - }, - { - ns: "Test.UDPAddrv4", - expected: "UDPAddrv4 doit être une adressse IPv4 UDP valide", - }, - { - ns: "Test.UDPAddrv6", - expected: "UDPAddrv6 doit être une adressse IPv6 UDP valide", - }, - { - ns: "Test.TCPAddr", - expected: "TCPAddr doit être une adressse TCP valide", - }, - { - ns: "Test.TCPAddrv4", - expected: "TCPAddrv4 doit être une adressse IPv4 TCP valide", - }, - { - ns: "Test.TCPAddrv6", - expected: "TCPAddrv6 doit être une adressse IPv6 TCP valide", - }, - { - ns: "Test.CIDR", - expected: "CIDR doit contenir une notation CIDR valide", - }, - { - ns: "Test.CIDRv4", - expected: "CIDRv4 doit contenir une notation CIDR valide pour une adresse IPv4", - }, - { - ns: "Test.CIDRv6", - expected: "CIDRv6 doit contenir une notation CIDR valide pour une adresse IPv6", - }, - { - ns: "Test.SSN", - expected: "SSN doit être un numéro SSN valide", - }, - { - ns: "Test.IP", - expected: "IP doit être une adressse IP valide", - }, - { - ns: "Test.IPv4", - expected: "IPv4 doit être une adressse IPv4 valide", - }, - { - ns: "Test.IPv6", - expected: "IPv6 doit être une adressse IPv6 valide", - }, - { - ns: "Test.DataURI", - expected: "DataURI doit contenir une URI data valide", - }, - { - ns: "Test.Latitude", - expected: "Latitude doit contenir des coordonnées latitude valides", - }, - { - ns: "Test.Longitude", - expected: "Longitude doit contenir des coordonnées longitudes valides", - }, - { - ns: "Test.MultiByte", - expected: "MultiByte doit contenir des caractères multioctets", - }, - { - ns: "Test.ASCII", - expected: "ASCII ne doit contenir que des caractères ascii", - }, - { - ns: "Test.PrintableASCII", - expected: "PrintableASCII ne doit contenir que des caractères ascii affichables", - }, - { - ns: "Test.UUID", - expected: "UUID doit être un UUID valid", - }, - { - ns: "Test.UUID3", - expected: "UUID3 doit être un UUID version 3 valid", - }, - { - ns: "Test.UUID4", - expected: "UUID4 doit être un UUID version 4 valid", - }, - { - ns: "Test.UUID5", - expected: "UUID5 doit être un UUID version 5 valid", - }, - { - ns: "Test.ISBN", - expected: "ISBN doit être un numéro ISBN valid", - }, - { - ns: "Test.ISBN10", - expected: "ISBN10 doit être un numéro ISBN-10 valid", - }, - { - ns: "Test.ISBN13", - expected: "ISBN13 doit être un numéro ISBN-13 valid", - }, - { - ns: "Test.Excludes", - expected: "Excludes ne doit pas contenir le texte 'text'", - }, - { - ns: "Test.ExcludesAll", - expected: "ExcludesAll ne doit pas contenir l'un des caractères suivants '!@#$'", - }, - { - ns: "Test.ExcludesRune", - expected: "ExcludesRune ne doit pas contenir ce qui suit '☻'", - }, - { - ns: "Test.ContainsAny", - expected: "ContainsAny doit contenir au moins l' un des caractères suivants '!@#$'", - }, - { - ns: "Test.Contains", - expected: "Contains doit contenir le texte 'purpose'", - }, - { - ns: "Test.Base64", - expected: "Base64 doit être une chaîne de caractères au format Base64 valide", - }, - { - ns: "Test.Email", - expected: "Email doit être une adresse email valide", - }, - { - ns: "Test.URL", - expected: "URL doit être une URL valide", - }, - { - ns: "Test.URI", - expected: "URI doit être une URI valide", - }, - { - ns: "Test.RGBColorString", - expected: "RGBColorString doit être une couleur au format RGB valide", - }, - { - ns: "Test.RGBAColorString", - expected: "RGBAColorString doit être une couleur au format RGBA valide", - }, - { - ns: "Test.HSLColorString", - expected: "HSLColorString doit être une couleur au format HSL valide", - }, - { - ns: "Test.HSLAColorString", - expected: "HSLAColorString doit être une couleur au format HSLA valide", - }, - { - ns: "Test.HexadecimalString", - expected: "HexadecimalString doit être une chaîne de caractères au format hexadécimal valide", - }, - { - ns: "Test.HexColorString", - expected: "HexColorString doit être une couleur au format HEX valide", - }, - { - ns: "Test.NumberString", - expected: "NumberString doit être un nombre valid", - }, - { - ns: "Test.NumericString", - expected: "NumericString doit être une valeur numérique valide", - }, - { - ns: "Test.AlphanumString", - expected: "AlphanumString ne doit contenir que des caractères alphanumériques", - }, - { - ns: "Test.AlphaString", - expected: "AlphaString ne doit contenir que des caractères alphabétiques", - }, - { - ns: "Test.LtFieldString", - expected: "LtFieldString doit être inférieur à MaxString", - }, - { - ns: "Test.LteFieldString", - expected: "LteFieldString doit être inférieur ou égal à MaxString", - }, - { - ns: "Test.GtFieldString", - expected: "GtFieldString doit être supérieur à MaxString", - }, - { - ns: "Test.GteFieldString", - expected: "GteFieldString doit être supérieur ou égal à MaxString", - }, - { - ns: "Test.NeFieldString", - expected: "NeFieldString ne doit pas être égal à EqFieldString", - }, - { - ns: "Test.LtCSFieldString", - expected: "LtCSFieldString doit être inférieur à Inner.LtCSFieldString", - }, - { - ns: "Test.LteCSFieldString", - expected: "LteCSFieldString doit être inférieur ou égal à Inner.LteCSFieldString", - }, - { - ns: "Test.GtCSFieldString", - expected: "GtCSFieldString doit être supérieur à Inner.GtCSFieldString", - }, - { - ns: "Test.GteCSFieldString", - expected: "GteCSFieldString doit être supérieur ou égal à Inner.GteCSFieldString", - }, - { - ns: "Test.NeCSFieldString", - expected: "NeCSFieldString ne doit pas être égal à Inner.NeCSFieldString", - }, - { - ns: "Test.EqCSFieldString", - expected: "EqCSFieldString doit être égal à Inner.EqCSFieldString", - }, - { - ns: "Test.EqFieldString", - expected: "EqFieldString doit être égal à MaxString", - }, - { - ns: "Test.GteString", - expected: "GteString doit faire une taille d'au moins 3 caractères", - }, - { - ns: "Test.GteNumber", - expected: "GteNumber doit être 5,56 ou plus", - }, - { - ns: "Test.GteMultiple", - expected: "GteMultiple doit contenir au moins 2 elements", - }, - { - ns: "Test.GteTime", - expected: "GteTime doit être après ou pendant la date et l'heure actuelle", - }, - { - ns: "Test.GtString", - expected: "GtString doit avoir une taille supérieur à 3 caractères", - }, - { - ns: "Test.GtNumber", - expected: "GtNumber doit être supérieur à 5,56", - }, - { - ns: "Test.GtMultiple", - expected: "GtMultiple doit contenir plus de 2 elements", - }, - { - ns: "Test.GtTime", - expected: "GtTime doit être après la date et l'heure actuelle", - }, - { - ns: "Test.LteString", - expected: "LteString doit faire une taille maximum de 3 caractères", - }, - { - ns: "Test.LteNumber", - expected: "LteNumber doit faire 5,56 ou moins", - }, - { - ns: "Test.LteMultiple", - expected: "LteMultiple doit contenir un maximum de 2 elements", - }, - { - ns: "Test.LteTime", - expected: "LteTime doit être avant ou pendant la date et l'heure actuelle", - }, - { - ns: "Test.LtString", - expected: "LtString doit avoir une taille inférieure à 3 caractères", - }, - { - ns: "Test.LtNumber", - expected: "LtNumber doit être inférieur à 5,56", - }, - { - ns: "Test.LtMultiple", - expected: "LtMultiple doit contenir mois de 2 elements", - }, - { - ns: "Test.LtTime", - expected: "LtTime doit être avant la date et l'heure actuelle", - }, - { - ns: "Test.NeString", - expected: "NeString ne doit pas être égal à ", - }, - { - ns: "Test.NeNumber", - expected: "NeNumber ne doit pas être égal à 0.00", - }, - { - ns: "Test.NeMultiple", - expected: "NeMultiple ne doit pas être égal à 0", - }, - { - ns: "Test.EqString", - expected: "EqString n'est pas égal à 3", - }, - { - ns: "Test.EqNumber", - expected: "EqNumber n'est pas égal à 2.33", - }, - { - ns: "Test.EqMultiple", - expected: "EqMultiple n'est pas égal à 7", - }, - { - ns: "Test.MaxString", - expected: "MaxString doit faire une taille maximum de 3 caractères", - }, - { - ns: "Test.MaxNumber", - expected: "MaxNumber doit être égal à 1 113,00 ou moins", - }, - { - ns: "Test.MaxMultiple", - expected: "MaxMultiple doit contenir au maximum 7 elements", - }, - { - ns: "Test.MinString", - expected: "MinString doit faire une taille minimum de 1 caractère", - }, - { - ns: "Test.MinNumber", - expected: "MinNumber doit être égal à 1 113,00 ou plus", - }, - { - ns: "Test.MinMultiple", - expected: "MinMultiple doit contenir au moins 7 elements", - }, - { - ns: "Test.LenString", - expected: "LenString doit faire une taille de 1 caractère", - }, - { - ns: "Test.LenNumber", - expected: "LenNumber doit être égal à 1 113,00", - }, - { - ns: "Test.LenMultiple", - expected: "LenMultiple doit contenir 7 elements", - }, - { - ns: "Test.RequiredString", - expected: "RequiredString est un champ obligatoire", - }, - { - ns: "Test.RequiredNumber", - expected: "RequiredNumber est un champ obligatoire", - }, - { - ns: "Test.RequiredMultiple", - expected: "RequiredMultiple est un champ obligatoire", - }, - { - ns: "Test.StrPtrMinLen", - expected: "StrPtrMinLen doit faire une taille minimum de 10 caractères", - }, - { - ns: "Test.StrPtrMaxLen", - expected: "StrPtrMaxLen doit faire une taille maximum de 1 caractère", - }, - { - ns: "Test.StrPtrLen", - expected: "StrPtrLen doit faire une taille de 2 caractères", - }, - { - ns: "Test.StrPtrLt", - expected: "StrPtrLt doit avoir une taille inférieure à 1 caractère", - }, - { - ns: "Test.StrPtrLte", - expected: "StrPtrLte doit faire une taille maximum de 1 caractère", - }, - { - ns: "Test.StrPtrGt", - expected: "StrPtrGt doit avoir une taille supérieur à 10 caractères", - }, - { - ns: "Test.StrPtrGte", - expected: "StrPtrGte doit faire une taille d'au moins 10 caractères", - }, - { - ns: "Test.OneOfString", - expected: "OneOfString doit être l'un des choix suivants [red green]", - }, - { - ns: "Test.OneOfInt", - expected: "OneOfInt doit être l'un des choix suivants [5 63]", - }, - } - - for _, tt := range tests { - - var fe validator.FieldError - - for _, e := range errs { - if tt.ns == e.Namespace() { - fe = e - break - } - } - - NotEqual(t, fe, nil) - Equal(t, tt.expected, fe.Translate(trans)) - } - -} diff --git a/go-playground/validator/v10/translations/id/id.go b/go-playground/validator/v10/translations/id/id.go deleted file mode 100644 index 594e8c1..0000000 --- a/go-playground/validator/v10/translations/id/id.go +++ /dev/null @@ -1,1365 +0,0 @@ -package id - -import ( - "fmt" - "log" - "reflect" - "strconv" - "strings" - "time" - - "git.ningdatech.com/ningda/gin_valid/go-playground/locales" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -// RegisterDefaultTranslations registers a set of default translations -// for all built in tag's in validator; you may add your own as desired. -func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (err error) { - - translations := []struct { - tag string - translation string - override bool - customRegisFunc validator.RegisterTranslationsFunc - customTransFunc validator.TranslationFunc - }{ - { - tag: "required", - translation: "{0} wajib diisi", - override: false, - }, - { - tag: "len", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("len-string", "panjang {0} harus {1}", false); err != nil { - return - } - - // if err = ut.AddCardinal("len-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("len-string-character", "{0} karakter", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("len-number", "{0} harus sama dengan {1}", false); err != nil { - return - } - - if err = ut.Add("len-items", "{0} harus berisi {1}", false); err != nil { - return - } - // if err = ut.AddCardinal("len-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("len-items-item", "{0} item", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("len-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("len-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-items", fe.Field(), c) - - default: - t, err = ut.T("len-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "min", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("min-string", "panjang minimal {0} adalah {1}", false); err != nil { - return - } - - // if err = ut.AddCardinal("min-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("min-string-character", "{0} karakter", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("min-number", "{0} harus {1} atau lebih besar", false); err != nil { - return - } - - if err = ut.Add("min-items", "panjang minimal {0} adalah {1}", false); err != nil { - return - } - // if err = ut.AddCardinal("min-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("min-items-item", "{0} item", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("min-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("min-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-items", fe.Field(), c) - - default: - t, err = ut.T("min-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "max", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("max-string", "panjang maksimal {0} adalah {1}", false); err != nil { - return - } - - // if err = ut.AddCardinal("max-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("max-string-character", "{0} karakter", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("max-number", "{0} harus {1} atau kurang", false); err != nil { - return - } - - if err = ut.Add("max-items", "{0} harus berisi maksimal {1}", false); err != nil { - return - } - // if err = ut.AddCardinal("max-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("max-items-item", "{0} item", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("max-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("max-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-items", fe.Field(), c) - - default: - t, err = ut.T("max-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eq", - translation: "{0} tidak sama dengan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ne", - translation: "{0} tidak sama dengan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lt-string", "panjang {0} harus kurang dari {1}", false); err != nil { - return - } - - // if err = ut.AddCardinal("lt-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("lt-string-character", "{0} karakter", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-number", "{0} harus kurang dari {1}", false); err != nil { - return - } - - if err = ut.Add("lt-items", "{0} harus berisi kurang dari {1}", false); err != nil { - return - } - - // if err = ut.AddCardinal("lt-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("lt-items-item", "{0} item", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-datetime", "{0} harus kurang dari tanggal & waktu saat ini", false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lte-string", "panjang maksimal {0} adalah {1}", false); err != nil { - return - } - - // if err = ut.AddCardinal("lte-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("lte-string-character", "{0} karakter", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-number", "{0} harus {1} atau kurang", false); err != nil { - return - } - - if err = ut.Add("lte-items", "{0} harus berisi maksimal {1}", false); err != nil { - return - } - - // if err = ut.AddCardinal("lte-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("lte-items-item", "{0} item", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-datetime", "{0} harus kurang dari atau sama dengan tanggal & waktu saat ini", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gt-string", "panjang {0} harus lebih dari {1}", false); err != nil { - return - } - - // if err = ut.AddCardinal("gt-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("gt-string-character", "{0} karakter", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-number", "{0} harus lebih besar dari {1}", false); err != nil { - return - } - - if err = ut.Add("gt-items", "{0} harus berisi lebih dari {1}", false); err != nil { - return - } - - // if err = ut.AddCardinal("gt-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("gt-items-item", "{0} item", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-datetime", "{0} harus lebih besar dari tanggal & waktu saat ini", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gte-string", "panjang minimal {0} adalah {1}", false); err != nil { - return - } - - // if err = ut.AddCardinal("gte-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("gte-string-character", "{0} karakter", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-number", "{0} harus {1} atau lebih besar", false); err != nil { - return - } - - if err = ut.Add("gte-items", "{0} harus berisi setidaknya {1}", false); err != nil { - return - } - - // if err = ut.AddCardinal("gte-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("gte-items-item", "{0} item", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-datetime", "{0} harus lebih besar dari atau sama dengan tanggal & waktu saat ini", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqfield", - translation: "{0} harus sama dengan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqcsfield", - translation: "{0} harus sama dengan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "necsfield", - translation: "{0} tidak sama dengan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtcsfield", - translation: "{0} harus lebih besar dari {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtecsfield", - translation: "{0} harus lebih besar dari atau sama dengan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltcsfield", - translation: "{0} harus kurang dari {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltecsfield", - translation: "{0} harus kurang dari atau sama dengan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "nefield", - translation: "{0} tidak sama dengan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtfield", - translation: "{0} harus lebih besar dari {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtefield", - translation: "{0} harus lebih besar dari atau sama dengan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltfield", - translation: "{0} harus kurang dari {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltefield", - translation: "{0} harus kurang dari atau sama dengan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "alpha", - translation: "{0} hanya dapat berisi karakter abjad", - override: false, - }, - { - tag: "alphanum", - translation: "{0} hanya dapat berisi karakter alfanumerik", - override: false, - }, - { - tag: "numeric", - translation: "{0} harus berupa nilai numerik yang valid", - override: false, - }, - { - tag: "number", - translation: "{0} harus berupa angka yang valid", - override: false, - }, - { - tag: "hexadecimal", - translation: "{0} harus berupa heksadesimal yang valid", - override: false, - }, - { - tag: "hexcolor", - translation: "{0} harus berupa warna HEX yang valid", - override: false, - }, - { - tag: "rgb", - translation: "{0} harus berupa warna RGB yang valid", - override: false, - }, - { - tag: "rgba", - translation: "{0} harus berupa warna RGBA yang valid", - override: false, - }, - { - tag: "hsl", - translation: "{0} harus berupa warna HSL yang valid", - override: false, - }, - { - tag: "hsla", - translation: "{0} harus berupa warna HSLA yang valid", - override: false, - }, - { - tag: "email", - translation: "{0} harus berupa alamat email yang valid", - override: false, - }, - { - tag: "url", - translation: "{0} harus berupa URL yang valid", - override: false, - }, - { - tag: "uri", - translation: "{0} harus berupa URI yang valid", - override: false, - }, - { - tag: "base64", - translation: "{0} harus berupa string Base64 yang valid", - override: false, - }, - { - tag: "contains", - translation: "{0} harus berisi teks '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "containsany", - translation: "{0} harus berisi setidaknya salah satu karakter berikut '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludes", - translation: "{0} tidak boleh berisi teks '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesall", - translation: "{0} tidak boleh berisi salah satu karakter berikut '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesrune", - translation: "{0} tidak boleh berisi '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "isbn", - translation: "{0} harus berupa nomor ISBN yang valid", - override: false, - }, - { - tag: "isbn10", - translation: "{0} harus berupa nomor ISBN-10 yang valid", - override: false, - }, - { - tag: "isbn13", - translation: "{0} harus berupa nomor ISBN-13 yang valid", - override: false, - }, - { - tag: "uuid", - translation: "{0} harus berupa UUID yang valid", - override: false, - }, - { - tag: "uuid3", - translation: "{0} harus berupa UUID versi 3 yang valid", - override: false, - }, - { - tag: "uuid4", - translation: "{0} harus berupa UUID versi 4 yang valid", - override: false, - }, - { - tag: "uuid5", - translation: "{0} harus berupa UUID versi 5 yang valid", - override: false, - }, - { - tag: "ascii", - translation: "{0} hanya boleh berisi karakter ascii", - override: false, - }, - { - tag: "printascii", - translation: "{0} hanya boleh berisi karakter ascii yang dapat dicetak", - override: false, - }, - { - tag: "multibyte", - translation: "{0} harus berisi karakter multibyte", - override: false, - }, - { - tag: "datauri", - translation: "{0} harus berisi URI Data yang valid", - override: false, - }, - { - tag: "latitude", - translation: "{0} harus berisi koordinat lintang yang valid", - override: false, - }, - { - tag: "longitude", - translation: "{0} harus berisi koordinat bujur yang valid", - override: false, - }, - { - tag: "ssn", - translation: "{0} harus berupa nomor SSN yang valid", - override: false, - }, - { - tag: "ipv4", - translation: "{0} harus berupa alamat IPv4 yang valid", - override: false, - }, - { - tag: "ipv6", - translation: "{0} harus berupa alamat IPv6 yang valid", - override: false, - }, - { - tag: "ip", - translation: "{0} harus berupa alamat IP yang valid", - override: false, - }, - { - tag: "cidr", - translation: "{0} harus berisi notasi CIDR yang valid", - override: false, - }, - { - tag: "cidrv4", - translation: "{0} harus berisi notasi CIDR yang valid untuk alamat IPv4", - override: false, - }, - { - tag: "cidrv6", - translation: "{0} harus berisi notasi CIDR yang valid untuk alamat IPv6", - override: false, - }, - { - tag: "tcp_addr", - translation: "{0} harus berupa alamat TCP yang valid", - override: false, - }, - { - tag: "tcp4_addr", - translation: "{0} harus berupa alamat TCP IPv4 yang valid", - override: false, - }, - { - tag: "tcp6_addr", - translation: "{0} harus berupa alamat TCP IPv6 yang valid", - override: false, - }, - { - tag: "udp_addr", - translation: "{0} harus berupa alamat UDP yang valid", - override: false, - }, - { - tag: "udp4_addr", - translation: "{0} harus berupa alamat IPv4 UDP yang valid", - override: false, - }, - { - tag: "udp6_addr", - translation: "{0} harus berupa alamat IPv6 UDP yang valid", - override: false, - }, - { - tag: "ip_addr", - translation: "{0} harus berupa alamat IP yang dapat dipecahkan", - override: false, - }, - { - tag: "ip4_addr", - translation: "{0} harus berupa alamat IPv4 yang dapat diatasi", - override: false, - }, - { - tag: "ip6_addr", - translation: "{0} harus berupa alamat IPv6 yang dapat diatasi", - override: false, - }, - { - tag: "unix_addr", - translation: "{0} harus berupa alamat UNIX yang dapat diatasi", - override: false, - }, - { - tag: "mac", - translation: "{0} harus berisi alamat MAC yang valid", - override: false, - }, - { - tag: "iscolor", - translation: "{0} harus berupa warna yang valid", - override: false, - }, - { - tag: "oneof", - translation: "{0} harus berupa salah satu dari [{1}]", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - s, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - return s - }, - }, - } - - for _, t := range translations { - - if t.customTransFunc != nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, t.customTransFunc) - - } else if t.customTransFunc != nil && t.customRegisFunc == nil { - - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), t.customTransFunc) - - } else if t.customTransFunc == nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, translateFunc) - - } else { - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), translateFunc) - } - - if err != nil { - return - } - } - - return -} - -func registrationFunc(tag string, translation string, override bool) validator.RegisterTranslationsFunc { - - return func(ut ut.Translator) (err error) { - - if err = ut.Add(tag, translation, override); err != nil { - return - } - - return - - } - -} - -func translateFunc(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t -} diff --git a/go-playground/validator/v10/translations/id/id_test.go b/go-playground/validator/v10/translations/id/id_test.go deleted file mode 100644 index ae79a24..0000000 --- a/go-playground/validator/v10/translations/id/id_test.go +++ /dev/null @@ -1,634 +0,0 @@ -package id - -import ( - "testing" - "time" - - . "git.ningdatech.com/ningda/gin_valid/go-playground/assert/v2" - indonesia "git.ningdatech.com/ningda/gin_valid/go-playground/locales/id" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -func TestTranslations(t *testing.T) { - - idn := indonesia.New() - uni := ut.New(idn, idn) - trans, _ := uni.GetTranslator("id") - - validate := validator.New() - - err := RegisterDefaultTranslations(validate, trans) - Equal(t, err, nil) - - type Inner struct { - EqCSFieldString string - NeCSFieldString string - GtCSFieldString string - GteCSFieldString string - LtCSFieldString string - LteCSFieldString string - } - - type Test struct { - Inner Inner - RequiredString string `validate:"required"` - RequiredNumber int `validate:"required"` - RequiredMultiple []string `validate:"required"` - LenString string `validate:"len=1"` - LenNumber float64 `validate:"len=1113.00"` - LenMultiple []string `validate:"len=7"` - MinString string `validate:"min=1"` - MinNumber float64 `validate:"min=1113.00"` - MinMultiple []string `validate:"min=7"` - MaxString string `validate:"max=3"` - MaxNumber float64 `validate:"max=1113.00"` - MaxMultiple []string `validate:"max=7"` - EqString string `validate:"eq=3"` - EqNumber float64 `validate:"eq=2.33"` - EqMultiple []string `validate:"eq=7"` - NeString string `validate:"ne="` - NeNumber float64 `validate:"ne=0.00"` - NeMultiple []string `validate:"ne=0"` - LtString string `validate:"lt=3"` - LtNumber float64 `validate:"lt=5.56"` - LtMultiple []string `validate:"lt=2"` - LtTime time.Time `validate:"lt"` - LteString string `validate:"lte=3"` - LteNumber float64 `validate:"lte=5.56"` - LteMultiple []string `validate:"lte=2"` - LteTime time.Time `validate:"lte"` - GtString string `validate:"gt=3"` - GtNumber float64 `validate:"gt=5.56"` - GtMultiple []string `validate:"gt=2"` - GtTime time.Time `validate:"gt"` - GteString string `validate:"gte=3"` - GteNumber float64 `validate:"gte=5.56"` - GteMultiple []string `validate:"gte=2"` - GteTime time.Time `validate:"gte"` - EqFieldString string `validate:"eqfield=MaxString"` - EqCSFieldString string `validate:"eqcsfield=Inner.EqCSFieldString"` - NeCSFieldString string `validate:"necsfield=Inner.NeCSFieldString"` - GtCSFieldString string `validate:"gtcsfield=Inner.GtCSFieldString"` - GteCSFieldString string `validate:"gtecsfield=Inner.GteCSFieldString"` - LtCSFieldString string `validate:"ltcsfield=Inner.LtCSFieldString"` - LteCSFieldString string `validate:"ltecsfield=Inner.LteCSFieldString"` - NeFieldString string `validate:"nefield=EqFieldString"` - GtFieldString string `validate:"gtfield=MaxString"` - GteFieldString string `validate:"gtefield=MaxString"` - LtFieldString string `validate:"ltfield=MaxString"` - LteFieldString string `validate:"ltefield=MaxString"` - AlphaString string `validate:"alpha"` - AlphanumString string `validate:"alphanum"` - NumericString string `validate:"numeric"` - NumberString string `validate:"number"` - HexadecimalString string `validate:"hexadecimal"` - HexColorString string `validate:"hexcolor"` - RGBColorString string `validate:"rgb"` - RGBAColorString string `validate:"rgba"` - HSLColorString string `validate:"hsl"` - HSLAColorString string `validate:"hsla"` - Email string `validate:"email"` - URL string `validate:"url"` - URI string `validate:"uri"` - Base64 string `validate:"base64"` - Contains string `validate:"contains=tujuan"` - ContainsAny string `validate:"containsany=!@#$"` - Excludes string `validate:"excludes=text"` - ExcludesAll string `validate:"excludesall=!@#$"` - ExcludesRune string `validate:"excludesrune=☻"` - ISBN string `validate:"isbn"` - ISBN10 string `validate:"isbn10"` - ISBN13 string `validate:"isbn13"` - UUID string `validate:"uuid"` - UUID3 string `validate:"uuid3"` - UUID4 string `validate:"uuid4"` - UUID5 string `validate:"uuid5"` - ASCII string `validate:"ascii"` - PrintableASCII string `validate:"printascii"` - MultiByte string `validate:"multibyte"` - DataURI string `validate:"datauri"` - Latitude string `validate:"latitude"` - Longitude string `validate:"longitude"` - SSN string `validate:"ssn"` - IP string `validate:"ip"` - IPv4 string `validate:"ipv4"` - IPv6 string `validate:"ipv6"` - CIDR string `validate:"cidr"` - CIDRv4 string `validate:"cidrv4"` - CIDRv6 string `validate:"cidrv6"` - TCPAddr string `validate:"tcp_addr"` - TCPAddrv4 string `validate:"tcp4_addr"` - TCPAddrv6 string `validate:"tcp6_addr"` - UDPAddr string `validate:"udp_addr"` - UDPAddrv4 string `validate:"udp4_addr"` - UDPAddrv6 string `validate:"udp6_addr"` - IPAddr string `validate:"ip_addr"` - IPAddrv4 string `validate:"ip4_addr"` - IPAddrv6 string `validate:"ip6_addr"` - UinxAddr string `validate:"unix_addr"` // can't fail from within Go's net package currently, but maybe in the future - MAC string `validate:"mac"` - IsColor string `validate:"iscolor"` - StrPtrMinLen *string `validate:"min=10"` - StrPtrMaxLen *string `validate:"max=1"` - StrPtrLen *string `validate:"len=2"` - StrPtrLt *string `validate:"lt=1"` - StrPtrLte *string `validate:"lte=1"` - StrPtrGt *string `validate:"gt=10"` - StrPtrGte *string `validate:"gte=10"` - OneOfString string `validate:"oneof=merah hijau"` - OneOfInt int `validate:"oneof=5 63"` - } - - var test Test - - test.Inner.EqCSFieldString = "1234" - test.Inner.GtCSFieldString = "1234" - test.Inner.GteCSFieldString = "1234" - - test.MaxString = "1234" - test.MaxNumber = 2000 - test.MaxMultiple = make([]string, 9) - - test.LtString = "1234" - test.LtNumber = 6 - test.LtMultiple = make([]string, 3) - test.LtTime = time.Now().Add(time.Hour * 24) - - test.LteString = "1234" - test.LteNumber = 6 - test.LteMultiple = make([]string, 3) - test.LteTime = time.Now().Add(time.Hour * 24) - - test.LtFieldString = "12345" - test.LteFieldString = "12345" - - test.LtCSFieldString = "1234" - test.LteCSFieldString = "1234" - - test.AlphaString = "abc3" - test.AlphanumString = "abc3!" - test.NumericString = "12E.00" - test.NumberString = "12E" - - test.Excludes = "this is some test text" - test.ExcludesAll = "This is Great!" - test.ExcludesRune = "Love it ☻" - - test.ASCII = "カタカナ" - test.PrintableASCII = "カタカナ" - - test.MultiByte = "1234feerf" - - s := "toolong" - test.StrPtrMaxLen = &s - test.StrPtrLen = &s - - err = validate.Struct(test) - NotEqual(t, err, nil) - - errs, ok := err.(validator.ValidationErrors) - Equal(t, ok, true) - - tests := []struct { - ns string - expected string - }{ - { - ns: "Test.IsColor", - expected: "IsColor harus berupa warna yang valid", - }, - { - ns: "Test.MAC", - expected: "MAC harus berisi alamat MAC yang valid", - }, - { - ns: "Test.IPAddr", - expected: "IPAddr harus berupa alamat IP yang dapat dipecahkan", - }, - { - ns: "Test.IPAddrv4", - expected: "IPAddrv4 harus berupa alamat IPv4 yang dapat diatasi", - }, - { - ns: "Test.IPAddrv6", - expected: "IPAddrv6 harus berupa alamat IPv6 yang dapat diatasi", - }, - { - ns: "Test.UDPAddr", - expected: "UDPAddr harus berupa alamat UDP yang valid", - }, - { - ns: "Test.UDPAddrv4", - expected: "UDPAddrv4 harus berupa alamat IPv4 UDP yang valid", - }, - { - ns: "Test.UDPAddrv6", - expected: "UDPAddrv6 harus berupa alamat IPv6 UDP yang valid", - }, - { - ns: "Test.TCPAddr", - expected: "TCPAddr harus berupa alamat TCP yang valid", - }, - { - ns: "Test.TCPAddrv4", - expected: "TCPAddrv4 harus berupa alamat TCP IPv4 yang valid", - }, - { - ns: "Test.TCPAddrv6", - expected: "TCPAddrv6 harus berupa alamat TCP IPv6 yang valid", - }, - { - ns: "Test.CIDR", - expected: "CIDR harus berisi notasi CIDR yang valid", - }, - { - ns: "Test.CIDRv4", - expected: "CIDRv4 harus berisi notasi CIDR yang valid untuk alamat IPv4", - }, - { - ns: "Test.CIDRv6", - expected: "CIDRv6 harus berisi notasi CIDR yang valid untuk alamat IPv6", - }, - { - ns: "Test.SSN", - expected: "SSN harus berupa nomor SSN yang valid", - }, - { - ns: "Test.IP", - expected: "IP harus berupa alamat IP yang valid", - }, - { - ns: "Test.IPv4", - expected: "IPv4 harus berupa alamat IPv4 yang valid", - }, - { - ns: "Test.IPv6", - expected: "IPv6 harus berupa alamat IPv6 yang valid", - }, - { - ns: "Test.DataURI", - expected: "DataURI harus berisi URI Data yang valid", - }, - { - ns: "Test.Latitude", - expected: "Latitude harus berisi koordinat lintang yang valid", - }, - { - ns: "Test.Longitude", - expected: "Longitude harus berisi koordinat bujur yang valid", - }, - { - ns: "Test.MultiByte", - expected: "MultiByte harus berisi karakter multibyte", - }, - { - ns: "Test.ASCII", - expected: "ASCII hanya boleh berisi karakter ascii", - }, - { - ns: "Test.PrintableASCII", - expected: "PrintableASCII hanya boleh berisi karakter ascii yang dapat dicetak", - }, - { - ns: "Test.UUID", - expected: "UUID harus berupa UUID yang valid", - }, - { - ns: "Test.UUID3", - expected: "UUID3 harus berupa UUID versi 3 yang valid", - }, - { - ns: "Test.UUID4", - expected: "UUID4 harus berupa UUID versi 4 yang valid", - }, - { - ns: "Test.UUID5", - expected: "UUID5 harus berupa UUID versi 5 yang valid", - }, - { - ns: "Test.ISBN", - expected: "ISBN harus berupa nomor ISBN yang valid", - }, - { - ns: "Test.ISBN10", - expected: "ISBN10 harus berupa nomor ISBN-10 yang valid", - }, - { - ns: "Test.ISBN13", - expected: "ISBN13 harus berupa nomor ISBN-13 yang valid", - }, - { - ns: "Test.Excludes", - expected: "Excludes tidak boleh berisi teks 'text'", - }, - { - ns: "Test.ExcludesAll", - expected: "ExcludesAll tidak boleh berisi salah satu karakter berikut '!@#$'", - }, - { - ns: "Test.ExcludesRune", - expected: "ExcludesRune tidak boleh berisi '☻'", - }, - { - ns: "Test.ContainsAny", - expected: "ContainsAny harus berisi setidaknya salah satu karakter berikut '!@#$'", - }, - { - ns: "Test.Contains", - expected: "Contains harus berisi teks 'tujuan'", - }, - { - ns: "Test.Base64", - expected: "Base64 harus berupa string Base64 yang valid", - }, - { - ns: "Test.Email", - expected: "Email harus berupa alamat email yang valid", - }, - { - ns: "Test.URL", - expected: "URL harus berupa URL yang valid", - }, - { - ns: "Test.URI", - expected: "URI harus berupa URI yang valid", - }, - { - ns: "Test.RGBColorString", - expected: "RGBColorString harus berupa warna RGB yang valid", - }, - { - ns: "Test.RGBAColorString", - expected: "RGBAColorString harus berupa warna RGBA yang valid", - }, - { - ns: "Test.HSLColorString", - expected: "HSLColorString harus berupa warna HSL yang valid", - }, - { - ns: "Test.HSLAColorString", - expected: "HSLAColorString harus berupa warna HSLA yang valid", - }, - { - ns: "Test.HexadecimalString", - expected: "HexadecimalString harus berupa heksadesimal yang valid", - }, - { - ns: "Test.HexColorString", - expected: "HexColorString harus berupa warna HEX yang valid", - }, - { - ns: "Test.NumberString", - expected: "NumberString harus berupa angka yang valid", - }, - { - ns: "Test.NumericString", - expected: "NumericString harus berupa nilai numerik yang valid", - }, - { - ns: "Test.AlphanumString", - expected: "AlphanumString hanya dapat berisi karakter alfanumerik", - }, - { - ns: "Test.AlphaString", - expected: "AlphaString hanya dapat berisi karakter abjad", - }, - { - ns: "Test.LtFieldString", - expected: "LtFieldString harus kurang dari MaxString", - }, - { - ns: "Test.LteFieldString", - expected: "LteFieldString harus kurang dari atau sama dengan MaxString", - }, - { - ns: "Test.GtFieldString", - expected: "GtFieldString harus lebih besar dari MaxString", - }, - { - ns: "Test.GteFieldString", - expected: "GteFieldString harus lebih besar dari atau sama dengan MaxString", - }, - { - ns: "Test.NeFieldString", - expected: "NeFieldString tidak sama dengan EqFieldString", - }, - { - ns: "Test.LtCSFieldString", - expected: "LtCSFieldString harus kurang dari Inner.LtCSFieldString", - }, - { - ns: "Test.LteCSFieldString", - expected: "LteCSFieldString harus kurang dari atau sama dengan Inner.LteCSFieldString", - }, - { - ns: "Test.GtCSFieldString", - expected: "GtCSFieldString harus lebih besar dari Inner.GtCSFieldString", - }, - { - ns: "Test.GteCSFieldString", - expected: "GteCSFieldString harus lebih besar dari atau sama dengan Inner.GteCSFieldString", - }, - { - ns: "Test.NeCSFieldString", - expected: "NeCSFieldString tidak sama dengan Inner.NeCSFieldString", - }, - { - ns: "Test.EqCSFieldString", - expected: "EqCSFieldString harus sama dengan Inner.EqCSFieldString", - }, - { - ns: "Test.EqFieldString", - expected: "EqFieldString harus sama dengan MaxString", - }, - { - ns: "Test.GteString", - expected: "panjang minimal GteString adalah 3 karakter", - }, - { - ns: "Test.GteNumber", - expected: "GteNumber harus 5,56 atau lebih besar", - }, - { - ns: "Test.GteMultiple", - expected: "GteMultiple harus berisi setidaknya 2 item", - }, - { - ns: "Test.GteTime", - expected: "GteTime harus lebih besar dari atau sama dengan tanggal & waktu saat ini", - }, - { - ns: "Test.GtString", - expected: "panjang GtString harus lebih dari 3 karakter", - }, - { - ns: "Test.GtNumber", - expected: "GtNumber harus lebih besar dari 5,56", - }, - { - ns: "Test.GtMultiple", - expected: "GtMultiple harus berisi lebih dari 2 item", - }, - { - ns: "Test.GtTime", - expected: "GtTime harus lebih besar dari tanggal & waktu saat ini", - }, - { - ns: "Test.LteString", - expected: "panjang maksimal LteString adalah 3 karakter", - }, - { - ns: "Test.LteNumber", - expected: "LteNumber harus 5,56 atau kurang", - }, - { - ns: "Test.LteMultiple", - expected: "LteMultiple harus berisi maksimal 2 item", - }, - { - ns: "Test.LteTime", - expected: "LteTime harus kurang dari atau sama dengan tanggal & waktu saat ini", - }, - { - ns: "Test.LtString", - expected: "panjang LtString harus kurang dari 3 karakter", - }, - { - ns: "Test.LtNumber", - expected: "LtNumber harus kurang dari 5,56", - }, - { - ns: "Test.LtMultiple", - expected: "LtMultiple harus berisi kurang dari 2 item", - }, - { - ns: "Test.LtTime", - expected: "LtTime harus kurang dari tanggal & waktu saat ini", - }, - { - ns: "Test.NeString", - expected: "NeString tidak sama dengan ", - }, - { - ns: "Test.NeNumber", - expected: "NeNumber tidak sama dengan 0.00", - }, - { - ns: "Test.NeMultiple", - expected: "NeMultiple tidak sama dengan 0", - }, - { - ns: "Test.EqString", - expected: "EqString tidak sama dengan 3", - }, - { - ns: "Test.EqNumber", - expected: "EqNumber tidak sama dengan 2.33", - }, - { - ns: "Test.EqMultiple", - expected: "EqMultiple tidak sama dengan 7", - }, - { - ns: "Test.MaxString", - expected: "panjang maksimal MaxString adalah 3 karakter", - }, - { - ns: "Test.MaxNumber", - expected: "MaxNumber harus 1.113,00 atau kurang", - }, - { - ns: "Test.MaxMultiple", - expected: "MaxMultiple harus berisi maksimal 7 item", - }, - { - ns: "Test.MinString", - expected: "panjang minimal MinString adalah 1 karakter", - }, - { - ns: "Test.MinNumber", - expected: "MinNumber harus 1.113,00 atau lebih besar", - }, - { - ns: "Test.MinMultiple", - expected: "panjang minimal MinMultiple adalah 7 item", - }, - { - ns: "Test.LenString", - expected: "panjang LenString harus 1 karakter", - }, - { - ns: "Test.LenNumber", - expected: "LenNumber harus sama dengan 1.113,00", - }, - { - ns: "Test.LenMultiple", - expected: "LenMultiple harus berisi 7 item", - }, - { - ns: "Test.RequiredString", - expected: "RequiredString wajib diisi", - }, - { - ns: "Test.RequiredNumber", - expected: "RequiredNumber wajib diisi", - }, - { - ns: "Test.RequiredMultiple", - expected: "RequiredMultiple wajib diisi", - }, - { - ns: "Test.StrPtrMinLen", - expected: "panjang minimal StrPtrMinLen adalah 10 karakter", - }, - { - ns: "Test.StrPtrMaxLen", - expected: "panjang maksimal StrPtrMaxLen adalah 1 karakter", - }, - { - ns: "Test.StrPtrLen", - expected: "panjang StrPtrLen harus 2 karakter", - }, - { - ns: "Test.StrPtrLt", - expected: "panjang StrPtrLt harus kurang dari 1 karakter", - }, - { - ns: "Test.StrPtrLte", - expected: "panjang maksimal StrPtrLte adalah 1 karakter", - }, - { - ns: "Test.StrPtrGt", - expected: "panjang StrPtrGt harus lebih dari 10 karakter", - }, - { - ns: "Test.StrPtrGte", - expected: "panjang minimal StrPtrGte adalah 10 karakter", - }, - { - ns: "Test.OneOfString", - expected: "OneOfString harus berupa salah satu dari [merah hijau]", - }, - { - ns: "Test.OneOfInt", - expected: "OneOfInt harus berupa salah satu dari [5 63]", - }, - } - - for _, tt := range tests { - - var fe validator.FieldError - - for _, e := range errs { - if tt.ns == e.Namespace() { - fe = e - break - } - } - - NotEqual(t, fe, nil) - Equal(t, tt.expected, fe.Translate(trans)) - } - -} diff --git a/go-playground/validator/v10/translations/ja/ja.go b/go-playground/validator/v10/translations/ja/ja.go deleted file mode 100644 index 26c9367..0000000 --- a/go-playground/validator/v10/translations/ja/ja.go +++ /dev/null @@ -1,1421 +0,0 @@ -package ja - -import ( - "fmt" - "log" - "reflect" - "strconv" - "strings" - "time" - - "git.ningdatech.com/ningda/gin_valid/go-playground/locales" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -// RegisterDefaultTranslations registers a set of default translations -// for all built in tag's in validator; you may add your own as desired. -func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (err error) { - - translations := []struct { - tag string - translation string - override bool - customRegisFunc validator.RegisterTranslationsFunc - customTransFunc validator.TranslationFunc - }{ - { - tag: "required", - translation: "{0}は必須フィールドです", - override: false, - }, - { - tag: "len", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("len-string", "{0}の長さは{1}でなければなりません", false); err != nil { - return - } - - // if err = ut.AddCardinal("len-string-character", "{0}文字", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("len-string-character", "{0}文字", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("len-number", "{0}は{1}と等しくなければなりません", false); err != nil { - return - } - - if err = ut.Add("len-items", "{0}は{1}を含まなければなりません", false); err != nil { - return - } - // if err = ut.AddCardinal("len-items-item", "{0}つの項目", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("len-items-item", "{0}つの項目", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("len-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("len-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-items", fe.Field(), c) - - default: - t, err = ut.T("len-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "min", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("min-string", "{0}の長さは少なくとも{1}はなければなりません", false); err != nil { - return - } - - // if err = ut.AddCardinal("min-string-character", "{0}文字", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("min-string-character", "{0}文字", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("min-number", "{0}は{1}かより大きくなければなりません", false); err != nil { - return - } - - if err = ut.Add("min-items", "{0}は少なくとも{1}を含まなければなりません", false); err != nil { - return - } - // if err = ut.AddCardinal("min-items-item", "{0}つの項目", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("min-items-item", "{0}つの項目", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("min-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("min-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-items", fe.Field(), c) - - default: - t, err = ut.T("min-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "max", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("max-string", "{0}の長さは最大でも{1}でなければなりません", false); err != nil { - return - } - - // if err = ut.AddCardinal("max-string-character", "{0}文字", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("max-string-character", "{0}文字", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("max-number", "{0}は{1}かより小さくなければなりません", false); err != nil { - return - } - - if err = ut.Add("max-items", "{0}は最大でも{1}を含まなければなりません", false); err != nil { - return - } - // if err = ut.AddCardinal("max-items-item", "{0}つの項目", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("max-items-item", "{0}つの項目", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("max-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("max-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-items", fe.Field(), c) - - default: - t, err = ut.T("max-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eq", - translation: "{0}は{1}と等しくありません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ne", - customRegisFunc: func(ut ut.Translator) (err error) { - if err = ut.Add("ne-items", "{0}の項目の数は{1}と異ならなければなりません", false); err != nil { - fmt.Printf("ne customRegisFunc #1 error because of %v\n", err) - return - } - // if err = ut.AddCardinal("ne-items-item", "{0}個", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("ne-items-item", "{0}個", locales.PluralRuleOther, false); err != nil { - return - } - if err = ut.Add("ne", "{0}は{1}と異ならなければなりません", false); err != nil { - fmt.Printf("ne customRegisFunc #2 error because of %v\n", err) - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.Slice: - var c string - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("ne-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - t, err = ut.T("ne-items", fe.Field(), c) - default: - t, err = ut.T("ne", fe.Field(), fe.Param()) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lt-string", "{0}の長さは{1}よりも少なくなければなりません", false); err != nil { - return - } - - // if err = ut.AddCardinal("lt-string-character", "{0}文字", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("lt-string-character", "{0}文字", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-number", "{0}は{1}よりも小さくなければなりません", false); err != nil { - return - } - - if err = ut.Add("lt-items", "{0}は{1}よりも少ない項目を含まなければなりません", false); err != nil { - return - } - - // if err = ut.AddCardinal("lt-items-item", "{0}つの項目", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("lt-items-item", "{0}つの項目", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-datetime", "{0}は現時刻よりも前でなければなりません", false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lte-string", "{0}の長さは最大でも{1}でなければなりません", false); err != nil { - return - } - - // if err = ut.AddCardinal("lte-string-character", "{0}文字", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("lte-string-character", "{0}文字", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-number", "{0}は{1}かより小さくなければなりません", false); err != nil { - return - } - - if err = ut.Add("lte-items", "{0}は最大でも{1}を含まなければなりません", false); err != nil { - return - } - - // if err = ut.AddCardinal("lte-items-item", "{0}つの項目", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("lte-items-item", "{0}つの項目", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-datetime", "{0}は現時刻以前でなければなりません", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gt-string", "{0}の長さは{1}よりも多くなければなりません", false); err != nil { - return - } - - // if err = ut.AddCardinal("gt-string-character", "{0}文字", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("gt-string-character", "{0}文字", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-number", "{0}は{1}よりも大きくなければなりません", false); err != nil { - return - } - - if err = ut.Add("gt-items", "{0}は{1}よりも多い項目を含まなければなりません", false); err != nil { - return - } - - // if err = ut.AddCardinal("gt-items-item", "{0}つの項目", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("gt-items-item", "{0}つの項目", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-datetime", "{0}は現時刻よりも後でなければなりません", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gte-string", "{0}の長さは少なくとも{1}以上はなければなりません", false); err != nil { - return - } - - // if err = ut.AddCardinal("gte-string-character", "{0}文字", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("gte-string-character", "{0}文字", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-number", "{0}は{1}かより大きくなければなりません", false); err != nil { - return - } - - if err = ut.Add("gte-items", "{0}は少なくとも{1}を含まなければなりません", false); err != nil { - return - } - - // if err = ut.AddCardinal("gte-items-item", "{0}つの項目", locales.PluralRuleOne, false); err != nil { - // return - // } - - if err = ut.AddCardinal("gte-items-item", "{0}つの項目", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-datetime", "{0}は現時刻以降でなければなりません", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqfield", - translation: "{0}は{1}と等しくなければなりません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqcsfield", - translation: "{0}は{1}と等しくなければなりません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "necsfield", - translation: "{0}は{1}とは異ならなければなりません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtcsfield", - translation: "{0}は{1}よりも大きくなければなりません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtecsfield", - translation: "{0}は{1}以上でなければなりません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltcsfield", - translation: "{0}は{1}よりも小さくなければなりません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltecsfield", - translation: "{0}は{1}以下でなければなりません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "nefield", - translation: "{0}は{1}とは異ならなければなりません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtfield", - translation: "{0}は{1}よりも大きくなければなりません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtefield", - translation: "{0}は{1}以上でなければなりません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltfield", - translation: "{0}は{1}よりも小さくなければなりません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltefield", - translation: "{0}は{1}以下でなければなりません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "alpha", - translation: "{0}はアルファベットのみを含むことができます", - override: false, - }, - { - tag: "alphanum", - translation: "{0}はアルファベットと数字のみを含むことができます", - override: false, - }, - { - tag: "numeric", - translation: "{0}は正しい数字でなければなりません", - override: false, - }, - { - tag: "number", - translation: "{0}は正しい数でなければなりません", - override: false, - }, - { - tag: "hexadecimal", - translation: "{0}は正しい16進表記でなければなりません", - override: false, - }, - { - tag: "hexcolor", - translation: "{0}は正しいHEXカラーコードでなければなりません", - override: false, - }, - { - tag: "rgb", - translation: "{0}は正しいRGBカラーコードでなければなりません", - override: false, - }, - { - tag: "rgba", - translation: "{0}は正しいRGBAカラーコードでなければなりません", - override: false, - }, - { - tag: "hsl", - translation: "{0}は正しいHSLカラーコードでなければなりません", - override: false, - }, - { - tag: "hsla", - translation: "{0}は正しいHSLAカラーコードでなければなりません", - override: false, - }, - { - tag: "email", - translation: "{0}は正しいメールアドレスでなければなりません", - override: false, - }, - { - tag: "url", - translation: "{0}は正しいURLでなければなりません", - override: false, - }, - { - tag: "uri", - translation: "{0}は正しいURIでなければなりません", - override: false, - }, - { - tag: "base64", - translation: "{0}は正しいBase64文字列でなければなりません", - override: false, - }, - { - tag: "contains", - translation: "{0}は'{1}'を含まなければなりません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "containsany", - translation: "{0}は'{1}'の少なくとも1つを含まなければなりません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludes", - translation: "{0}には'{1}'というテキストを含むことはできません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesall", - translation: "{0}には'{1}'のどれも含めることはできません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesrune", - translation: "{0}には'{1}'を含めることはできません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "isbn", - translation: "{0}は正しいISBN番号でなければなりません", - override: false, - }, - { - tag: "isbn10", - translation: "{0}は正しいISBN-10番号でなければなりません", - override: false, - }, - { - tag: "isbn13", - translation: "{0}は正しいISBN-13番号でなければなりません", - override: false, - }, - { - tag: "uuid", - translation: "{0}は正しいUUIDでなければなりません", - override: false, - }, - { - tag: "uuid3", - translation: "{0}はバージョンが3の正しいUUIDでなければなりません", - override: false, - }, - { - tag: "uuid4", - translation: "{0}はバージョンが4の正しいUUIDでなければなりません", - override: false, - }, - { - tag: "uuid5", - translation: "{0}はバージョンが4の正しいUUIDでなければなりません", - override: false, - }, - { - tag: "ascii", - translation: "{0}はASCII文字のみを含まなければなりません", - override: false, - }, - { - tag: "printascii", - translation: "{0}は印刷可能なASCII文字のみを含まなければなりません", - override: false, - }, - { - tag: "multibyte", - translation: "{0}はマルチバイト文字を含まなければなりません", - override: false, - }, - { - tag: "datauri", - translation: "{0}は正しいデータURIを含まなければなりません", - override: false, - }, - { - tag: "latitude", - translation: "{0}は正しい緯度の座標を含まなければなりません", - override: false, - }, - { - tag: "longitude", - translation: "{0}は正しい経度の座標を含まなければなりません", - override: false, - }, - { - tag: "ssn", - translation: "{0}は正しい社会保障番号でなければなりません", - override: false, - }, - { - tag: "ipv4", - translation: "{0}は正しいIPv4アドレスでなければなりません", - override: false, - }, - { - tag: "ipv6", - translation: "{0}は正しいIPv6アドレスでなければなりません", - override: false, - }, - { - tag: "ip", - translation: "{0}は正しいIPアドレスでなければなりません", - override: false, - }, - { - tag: "cidr", - translation: "{0}は正しいCIDR表記を含まなければなりません", - override: false, - }, - { - tag: "cidrv4", - translation: "{0}はIPv4アドレスの正しいCIDR表記を含まなければなりません", - override: false, - }, - { - tag: "cidrv6", - translation: "{0}はIPv6アドレスの正しいCIDR表記を含まなければなりません", - override: false, - }, - { - tag: "tcp_addr", - translation: "{0}は正しいTCPアドレスでなければなりません", - override: false, - }, - { - tag: "tcp4_addr", - translation: "{0}は正しいIPv4のTCPアドレスでなければなりません", - override: false, - }, - { - tag: "tcp6_addr", - translation: "{0}は正しいIPv6のTCPアドレスでなければなりません", - override: false, - }, - { - tag: "udp_addr", - translation: "{0}は正しいUDPアドレスでなければなりません", - override: false, - }, - { - tag: "udp4_addr", - translation: "{0}は正しいIPv4のUDPアドレスでなければなりません", - override: false, - }, - { - tag: "udp6_addr", - translation: "{0}は正しいIPv6のUDPアドレスでなければなりません", - override: false, - }, - { - tag: "ip_addr", - translation: "{0}は解決可能なIPアドレスでなければなりません", - override: false, - }, - { - tag: "ip4_addr", - translation: "{0}は解決可能なIPv4アドレスでなければなりません", - override: false, - }, - { - tag: "ip6_addr", - translation: "{0}は解決可能なIPv6アドレスでなければなりません", - override: false, - }, - { - tag: "unix_addr", - translation: "{0}は解決可能なUNIXアドレスでなければなりません", - override: false, - }, - { - tag: "mac", - translation: "{0}は正しいMACアドレスを含まなければなりません", - override: false, - }, - { - tag: "iscolor", - translation: "{0}は正しい色でなければなりません", - override: false, - }, - { - tag: "oneof", - translation: "{0}は[{1}]のうちのいずれかでなければなりません", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - s, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - return s - }, - }, - } - - for _, t := range translations { - - if t.customTransFunc != nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, t.customTransFunc) - - } else if t.customTransFunc != nil && t.customRegisFunc == nil { - - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), t.customTransFunc) - - } else if t.customTransFunc == nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, translateFunc) - - } else { - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), translateFunc) - } - - if err != nil { - return - } - } - - return -} - -func registrationFunc(tag string, translation string, override bool) validator.RegisterTranslationsFunc { - - return func(ut ut.Translator) (err error) { - - if err = ut.Add(tag, translation, override); err != nil { - return - } - - return - - } - -} - -func translateFunc(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t -} diff --git a/go-playground/validator/v10/translations/ja/ja_test.go b/go-playground/validator/v10/translations/ja/ja_test.go deleted file mode 100644 index 8b97d17..0000000 --- a/go-playground/validator/v10/translations/ja/ja_test.go +++ /dev/null @@ -1,634 +0,0 @@ -package ja - -import ( - "testing" - "time" - - . "git.ningdatech.com/ningda/gin_valid/go-playground/assert/v2" - ja_locale "git.ningdatech.com/ningda/gin_valid/go-playground/locales/ja" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" - ut "github.com/go-playground/universal-translator" -) - -func TestTranslations(t *testing.T) { - - japanese := ja_locale.New() - uni := ut.New(japanese, japanese) - trans, _ := uni.GetTranslator("ja") - - validate := validator.New() - - err := RegisterDefaultTranslations(validate, trans) - Equal(t, err, nil) - - type Inner struct { - EqCSFieldString string - NeCSFieldString string - GtCSFieldString string - GteCSFieldString string - LtCSFieldString string - LteCSFieldString string - } - - type Test struct { - Inner Inner - RequiredString string `validate:"required"` - RequiredNumber int `validate:"required"` - RequiredMultiple []string `validate:"required"` - LenString string `validate:"len=1"` - LenNumber float64 `validate:"len=1113.00"` - LenMultiple []string `validate:"len=7"` - MinString string `validate:"min=1"` - MinNumber float64 `validate:"min=1113.00"` - MinMultiple []string `validate:"min=7"` - MaxString string `validate:"max=3"` - MaxNumber float64 `validate:"max=1113.00"` - MaxMultiple []string `validate:"max=7"` - EqString string `validate:"eq=3"` - EqNumber float64 `validate:"eq=2.33"` - EqMultiple []string `validate:"eq=7"` - NeString string `validate:"ne="` - NeNumber float64 `validate:"ne=0.00"` - NeMultiple []string `validate:"ne=0"` - LtString string `validate:"lt=3"` - LtNumber float64 `validate:"lt=5.56"` - LtMultiple []string `validate:"lt=2"` - LtTime time.Time `validate:"lt"` - LteString string `validate:"lte=3"` - LteNumber float64 `validate:"lte=5.56"` - LteMultiple []string `validate:"lte=2"` - LteTime time.Time `validate:"lte"` - GtString string `validate:"gt=3"` - GtNumber float64 `validate:"gt=5.56"` - GtMultiple []string `validate:"gt=2"` - GtTime time.Time `validate:"gt"` - GteString string `validate:"gte=3"` - GteNumber float64 `validate:"gte=5.56"` - GteMultiple []string `validate:"gte=2"` - GteTime time.Time `validate:"gte"` - EqFieldString string `validate:"eqfield=MaxString"` - EqCSFieldString string `validate:"eqcsfield=Inner.EqCSFieldString"` - NeCSFieldString string `validate:"necsfield=Inner.NeCSFieldString"` - GtCSFieldString string `validate:"gtcsfield=Inner.GtCSFieldString"` - GteCSFieldString string `validate:"gtecsfield=Inner.GteCSFieldString"` - LtCSFieldString string `validate:"ltcsfield=Inner.LtCSFieldString"` - LteCSFieldString string `validate:"ltecsfield=Inner.LteCSFieldString"` - NeFieldString string `validate:"nefield=EqFieldString"` - GtFieldString string `validate:"gtfield=MaxString"` - GteFieldString string `validate:"gtefield=MaxString"` - LtFieldString string `validate:"ltfield=MaxString"` - LteFieldString string `validate:"ltefield=MaxString"` - AlphaString string `validate:"alpha"` - AlphanumString string `validate:"alphanum"` - NumericString string `validate:"numeric"` - NumberString string `validate:"number"` - HexadecimalString string `validate:"hexadecimal"` - HexColorString string `validate:"hexcolor"` - RGBColorString string `validate:"rgb"` - RGBAColorString string `validate:"rgba"` - HSLColorString string `validate:"hsl"` - HSLAColorString string `validate:"hsla"` - Email string `validate:"email"` - URL string `validate:"url"` - URI string `validate:"uri"` - Base64 string `validate:"base64"` - Contains string `validate:"contains=purpose"` - ContainsAny string `validate:"containsany=!@#$"` - Excludes string `validate:"excludes=text"` - ExcludesAll string `validate:"excludesall=!@#$"` - ExcludesRune string `validate:"excludesrune=☻"` - ISBN string `validate:"isbn"` - ISBN10 string `validate:"isbn10"` - ISBN13 string `validate:"isbn13"` - UUID string `validate:"uuid"` - UUID3 string `validate:"uuid3"` - UUID4 string `validate:"uuid4"` - UUID5 string `validate:"uuid5"` - ASCII string `validate:"ascii"` - PrintableASCII string `validate:"printascii"` - MultiByte string `validate:"multibyte"` - DataURI string `validate:"datauri"` - Latitude string `validate:"latitude"` - Longitude string `validate:"longitude"` - SSN string `validate:"ssn"` - IP string `validate:"ip"` - IPv4 string `validate:"ipv4"` - IPv6 string `validate:"ipv6"` - CIDR string `validate:"cidr"` - CIDRv4 string `validate:"cidrv4"` - CIDRv6 string `validate:"cidrv6"` - TCPAddr string `validate:"tcp_addr"` - TCPAddrv4 string `validate:"tcp4_addr"` - TCPAddrv6 string `validate:"tcp6_addr"` - UDPAddr string `validate:"udp_addr"` - UDPAddrv4 string `validate:"udp4_addr"` - UDPAddrv6 string `validate:"udp6_addr"` - IPAddr string `validate:"ip_addr"` - IPAddrv4 string `validate:"ip4_addr"` - IPAddrv6 string `validate:"ip6_addr"` - UinxAddr string `validate:"unix_addr"` // can't fail from within Go's net package currently, but maybe in the future - MAC string `validate:"mac"` - IsColor string `validate:"iscolor"` - StrPtrMinLen *string `validate:"min=10"` - StrPtrMaxLen *string `validate:"max=1"` - StrPtrLen *string `validate:"len=2"` - StrPtrLt *string `validate:"lt=1"` - StrPtrLte *string `validate:"lte=1"` - StrPtrGt *string `validate:"gt=10"` - StrPtrGte *string `validate:"gte=10"` - OneOfString string `validate:"oneof=red green"` - OneOfInt int `validate:"oneof=5 63"` - } - - var test Test - - test.Inner.EqCSFieldString = "1234" - test.Inner.GtCSFieldString = "1234" - test.Inner.GteCSFieldString = "1234" - - test.MaxString = "1234" - test.MaxNumber = 2000 - test.MaxMultiple = make([]string, 9) - - test.LtString = "1234" - test.LtNumber = 6 - test.LtMultiple = make([]string, 3) - test.LtTime = time.Now().Add(time.Hour * 24) - - test.LteString = "1234" - test.LteNumber = 6 - test.LteMultiple = make([]string, 3) - test.LteTime = time.Now().Add(time.Hour * 24) - - test.LtFieldString = "12345" - test.LteFieldString = "12345" - - test.LtCSFieldString = "1234" - test.LteCSFieldString = "1234" - - test.AlphaString = "abc3" - test.AlphanumString = "abc3!" - test.NumericString = "12E.00" - test.NumberString = "12E" - - test.Excludes = "this is some test text" - test.ExcludesAll = "This is Great!" - test.ExcludesRune = "Love it ☻" - - test.ASCII = "カタカナ" - test.PrintableASCII = "カタカナ" - - test.MultiByte = "1234feerf" - - s := "toolong" - test.StrPtrMaxLen = &s - test.StrPtrLen = &s - - err = validate.Struct(test) - NotEqual(t, err, nil) - - errs, ok := err.(validator.ValidationErrors) - Equal(t, ok, true) - - tests := []struct { - ns string - expected string - }{ - { - ns: "Test.IsColor", - expected: "IsColorは正しい色でなければなりません", - }, - { - ns: "Test.MAC", - expected: "MACは正しいMACアドレスを含まなければなりません", - }, - { - ns: "Test.IPAddr", - expected: "IPAddrは解決可能なIPアドレスでなければなりません", - }, - { - ns: "Test.IPAddrv4", - expected: "IPAddrv4は解決可能なIPv4アドレスでなければなりません", - }, - { - ns: "Test.IPAddrv6", - expected: "IPAddrv6は解決可能なIPv6アドレスでなければなりません", - }, - { - ns: "Test.UDPAddr", - expected: "UDPAddrは正しいUDPアドレスでなければなりません", - }, - { - ns: "Test.UDPAddrv4", - expected: "UDPAddrv4は正しいIPv4のUDPアドレスでなければなりません", - }, - { - ns: "Test.UDPAddrv6", - expected: "UDPAddrv6は正しいIPv6のUDPアドレスでなければなりません", - }, - { - ns: "Test.TCPAddr", - expected: "TCPAddrは正しいTCPアドレスでなければなりません", - }, - { - ns: "Test.TCPAddrv4", - expected: "TCPAddrv4は正しいIPv4のTCPアドレスでなければなりません", - }, - { - ns: "Test.TCPAddrv6", - expected: "TCPAddrv6は正しいIPv6のTCPアドレスでなければなりません", - }, - { - ns: "Test.CIDR", - expected: "CIDRは正しいCIDR表記を含まなければなりません", - }, - { - ns: "Test.CIDRv4", - expected: "CIDRv4はIPv4アドレスの正しいCIDR表記を含まなければなりません", - }, - { - ns: "Test.CIDRv6", - expected: "CIDRv6はIPv6アドレスの正しいCIDR表記を含まなければなりません", - }, - { - ns: "Test.SSN", - expected: "SSNは正しい社会保障番号でなければなりません", - }, - { - ns: "Test.IP", - expected: "IPは正しいIPアドレスでなければなりません", - }, - { - ns: "Test.IPv4", - expected: "IPv4は正しいIPv4アドレスでなければなりません", - }, - { - ns: "Test.IPv6", - expected: "IPv6は正しいIPv6アドレスでなければなりません", - }, - { - ns: "Test.DataURI", - expected: "DataURIは正しいデータURIを含まなければなりません", - }, - { - ns: "Test.Latitude", - expected: "Latitudeは正しい緯度の座標を含まなければなりません", - }, - { - ns: "Test.Longitude", - expected: "Longitudeは正しい経度の座標を含まなければなりません", - }, - { - ns: "Test.MultiByte", - expected: "MultiByteはマルチバイト文字を含まなければなりません", - }, - { - ns: "Test.ASCII", - expected: "ASCIIはASCII文字のみを含まなければなりません", - }, - { - ns: "Test.PrintableASCII", - expected: "PrintableASCIIは印刷可能なASCII文字のみを含まなければなりません", - }, - { - ns: "Test.UUID", - expected: "UUIDは正しいUUIDでなければなりません", - }, - { - ns: "Test.UUID3", - expected: "UUID3はバージョンが3の正しいUUIDでなければなりません", - }, - { - ns: "Test.UUID4", - expected: "UUID4はバージョンが4の正しいUUIDでなければなりません", - }, - { - ns: "Test.UUID5", - expected: "UUID5はバージョンが4の正しいUUIDでなければなりません", - }, - { - ns: "Test.ISBN", - expected: "ISBNは正しいISBN番号でなければなりません", - }, - { - ns: "Test.ISBN10", - expected: "ISBN10は正しいISBN-10番号でなければなりません", - }, - { - ns: "Test.ISBN13", - expected: "ISBN13は正しいISBN-13番号でなければなりません", - }, - { - ns: "Test.Excludes", - expected: "Excludesには'text'というテキストを含むことはできません", - }, - { - ns: "Test.ExcludesAll", - expected: "ExcludesAllには'!@#$'のどれも含めることはできません", - }, - { - ns: "Test.ExcludesRune", - expected: "ExcludesRuneには'☻'を含めることはできません", - }, - { - ns: "Test.ContainsAny", - expected: "ContainsAnyは'!@#$'の少なくとも1つを含まなければなりません", - }, - { - ns: "Test.Contains", - expected: "Containsは'purpose'を含まなければなりません", - }, - { - ns: "Test.Base64", - expected: "Base64は正しいBase64文字列でなければなりません", - }, - { - ns: "Test.Email", - expected: "Emailは正しいメールアドレスでなければなりません", - }, - { - ns: "Test.URL", - expected: "URLは正しいURLでなければなりません", - }, - { - ns: "Test.URI", - expected: "URIは正しいURIでなければなりません", - }, - { - ns: "Test.RGBColorString", - expected: "RGBColorStringは正しいRGBカラーコードでなければなりません", - }, - { - ns: "Test.RGBAColorString", - expected: "RGBAColorStringは正しいRGBAカラーコードでなければなりません", - }, - { - ns: "Test.HSLColorString", - expected: "HSLColorStringは正しいHSLカラーコードでなければなりません", - }, - { - ns: "Test.HSLAColorString", - expected: "HSLAColorStringは正しいHSLAカラーコードでなければなりません", - }, - { - ns: "Test.HexadecimalString", - expected: "HexadecimalStringは正しい16進表記でなければなりません", - }, - { - ns: "Test.HexColorString", - expected: "HexColorStringは正しいHEXカラーコードでなければなりません", - }, - { - ns: "Test.NumberString", - expected: "NumberStringは正しい数でなければなりません", - }, - { - ns: "Test.NumericString", - expected: "NumericStringは正しい数字でなければなりません", - }, - { - ns: "Test.AlphanumString", - expected: "AlphanumStringはアルファベットと数字のみを含むことができます", - }, - { - ns: "Test.AlphaString", - expected: "AlphaStringはアルファベットのみを含むことができます", - }, - { - ns: "Test.LtFieldString", - expected: "LtFieldStringはMaxStringよりも小さくなければなりません", - }, - { - ns: "Test.LteFieldString", - expected: "LteFieldStringはMaxString以下でなければなりません", - }, - { - ns: "Test.GtFieldString", - expected: "GtFieldStringはMaxStringよりも大きくなければなりません", - }, - { - ns: "Test.GteFieldString", - expected: "GteFieldStringはMaxString以上でなければなりません", - }, - { - ns: "Test.NeFieldString", - expected: "NeFieldStringはEqFieldStringとは異ならなければなりません", - }, - { - ns: "Test.LtCSFieldString", - expected: "LtCSFieldStringはInner.LtCSFieldStringよりも小さくなければなりません", - }, - { - ns: "Test.LteCSFieldString", - expected: "LteCSFieldStringはInner.LteCSFieldString以下でなければなりません", - }, - { - ns: "Test.GtCSFieldString", - expected: "GtCSFieldStringはInner.GtCSFieldStringよりも大きくなければなりません", - }, - { - ns: "Test.GteCSFieldString", - expected: "GteCSFieldStringはInner.GteCSFieldString以上でなければなりません", - }, - { - ns: "Test.NeCSFieldString", - expected: "NeCSFieldStringはInner.NeCSFieldStringとは異ならなければなりません", - }, - { - ns: "Test.EqCSFieldString", - expected: "EqCSFieldStringはInner.EqCSFieldStringと等しくなければなりません", - }, - { - ns: "Test.EqFieldString", - expected: "EqFieldStringはMaxStringと等しくなければなりません", - }, - { - ns: "Test.GteString", - expected: "GteStringの長さは少なくとも3文字以上はなければなりません", - }, - { - ns: "Test.GteNumber", - expected: "GteNumberは5.56かより大きくなければなりません", - }, - { - ns: "Test.GteMultiple", - expected: "GteMultipleは少なくとも2つの項目を含まなければなりません", - }, - { - ns: "Test.GteTime", - expected: "GteTimeは現時刻以降でなければなりません", - }, - { - ns: "Test.GtString", - expected: "GtStringの長さは3文字よりも多くなければなりません", - }, - { - ns: "Test.GtNumber", - expected: "GtNumberは5.56よりも大きくなければなりません", - }, - { - ns: "Test.GtMultiple", - expected: "GtMultipleは2つの項目よりも多い項目を含まなければなりません", - }, - { - ns: "Test.GtTime", - expected: "GtTimeは現時刻よりも後でなければなりません", - }, - { - ns: "Test.LteString", - expected: "LteStringの長さは最大でも3文字でなければなりません", - }, - { - ns: "Test.LteNumber", - expected: "LteNumberは5.56かより小さくなければなりません", - }, - { - ns: "Test.LteMultiple", - expected: "LteMultipleは最大でも2つの項目を含まなければなりません", - }, - { - ns: "Test.LteTime", - expected: "LteTimeは現時刻以前でなければなりません", - }, - { - ns: "Test.LtString", - expected: "LtStringの長さは3文字よりも少なくなければなりません", - }, - { - ns: "Test.LtNumber", - expected: "LtNumberは5.56よりも小さくなければなりません", - }, - { - ns: "Test.LtMultiple", - expected: "LtMultipleは2つの項目よりも少ない項目を含まなければなりません", - }, - { - ns: "Test.LtTime", - expected: "LtTimeは現時刻よりも前でなければなりません", - }, - { - ns: "Test.NeString", - expected: "NeStringはと異ならなければなりません", - }, - { - ns: "Test.NeNumber", - expected: "NeNumberは0.00と異ならなければなりません", - }, - { - ns: "Test.NeMultiple", - expected: "NeMultipleの項目の数は0個と異ならなければなりません", - }, - { - ns: "Test.EqString", - expected: "EqStringは3と等しくありません", - }, - { - ns: "Test.EqNumber", - expected: "EqNumberは2.33と等しくありません", - }, - { - ns: "Test.EqMultiple", - expected: "EqMultipleは7と等しくありません", - }, - { - ns: "Test.MaxString", - expected: "MaxStringの長さは最大でも3文字でなければなりません", - }, - { - ns: "Test.MaxNumber", - expected: "MaxNumberは1,113.00かより小さくなければなりません", - }, - { - ns: "Test.MaxMultiple", - expected: "MaxMultipleは最大でも7つの項目を含まなければなりません", - }, - { - ns: "Test.MinString", - expected: "MinStringの長さは少なくとも1文字はなければなりません", - }, - { - ns: "Test.MinNumber", - expected: "MinNumberは1,113.00かより大きくなければなりません", - }, - { - ns: "Test.MinMultiple", - expected: "MinMultipleは少なくとも7つの項目を含まなければなりません", - }, - { - ns: "Test.LenString", - expected: "LenStringの長さは1文字でなければなりません", - }, - { - ns: "Test.LenNumber", - expected: "LenNumberは1,113.00と等しくなければなりません", - }, - { - ns: "Test.LenMultiple", - expected: "LenMultipleは7つの項目を含まなければなりません", - }, - { - ns: "Test.RequiredString", - expected: "RequiredStringは必須フィールドです", - }, - { - ns: "Test.RequiredNumber", - expected: "RequiredNumberは必須フィールドです", - }, - { - ns: "Test.RequiredMultiple", - expected: "RequiredMultipleは必須フィールドです", - }, - { - ns: "Test.StrPtrMinLen", - expected: "StrPtrMinLenの長さは少なくとも10文字はなければなりません", - }, - { - ns: "Test.StrPtrMaxLen", - expected: "StrPtrMaxLenの長さは最大でも1文字でなければなりません", - }, - { - ns: "Test.StrPtrLen", - expected: "StrPtrLenの長さは2文字でなければなりません", - }, - { - ns: "Test.StrPtrLt", - expected: "StrPtrLtの長さは1文字よりも少なくなければなりません", - }, - { - ns: "Test.StrPtrLte", - expected: "StrPtrLteの長さは最大でも1文字でなければなりません", - }, - { - ns: "Test.StrPtrGt", - expected: "StrPtrGtの長さは10文字よりも多くなければなりません", - }, - { - ns: "Test.StrPtrGte", - expected: "StrPtrGteの長さは少なくとも10文字以上はなければなりません", - }, - { - ns: "Test.OneOfString", - expected: "OneOfStringは[red green]のうちのいずれかでなければなりません", - }, - { - ns: "Test.OneOfInt", - expected: "OneOfIntは[5 63]のうちのいずれかでなければなりません", - }, - } - - for _, tt := range tests { - - var fe validator.FieldError - - for _, e := range errs { - if tt.ns == e.Namespace() { - fe = e - break - } - } - - NotEqual(t, fe, nil) - Equal(t, tt.expected, fe.Translate(trans)) - } - -} diff --git a/go-playground/validator/v10/translations/nl/nl.go b/go-playground/validator/v10/translations/nl/nl.go deleted file mode 100644 index 8f49a1d..0000000 --- a/go-playground/validator/v10/translations/nl/nl.go +++ /dev/null @@ -1,1365 +0,0 @@ -package nl - -import ( - "fmt" - "log" - "reflect" - "strconv" - "strings" - "time" - - "git.ningdatech.com/ningda/gin_valid/go-playground/locales" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -// RegisterDefaultTranslations registers a set of default translations -// for all built in tag's in validator; you may add your own as desired. -func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (err error) { - - translations := []struct { - tag string - translation string - override bool - customRegisFunc validator.RegisterTranslationsFunc - customTransFunc validator.TranslationFunc - }{ - { - tag: "required", - translation: "{0} is een verplicht veld", - override: false, - }, - { - tag: "len", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("len-string", "{0} moet {1} lang zijn", false); err != nil { - return - } - - if err = ut.AddCardinal("len-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("len-string-character", "{0} karakters", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("len-number", "{0} moet gelijk zijn aan {1}", false); err != nil { - return - } - - if err = ut.Add("len-items", "{0} moet {1} bevatten", false); err != nil { - return - } - if err = ut.AddCardinal("len-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("len-items-item", "{0} items", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("len-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("len-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-items", fe.Field(), c) - - default: - t, err = ut.T("len-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "min", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("min-string", "{0} moet tenminste {1} lang zijn", false); err != nil { - return - } - - if err = ut.AddCardinal("min-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("min-string-character", "{0} karakters", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("min-number", "{0} moet {1} of groter zijn", false); err != nil { - return - } - - if err = ut.Add("min-items", "{0} moet tenminste {1} bevatten", false); err != nil { - return - } - if err = ut.AddCardinal("min-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("min-items-item", "{0} items", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("min-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("min-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-items", fe.Field(), c) - - default: - t, err = ut.T("min-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "max", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("max-string", "{0} mag maximaal {1} lang zijn", false); err != nil { - return - } - - if err = ut.AddCardinal("max-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("max-string-character", "{0} karakters", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("max-number", "{0} moet {1} of kleiner zijn", false); err != nil { - return - } - - if err = ut.Add("max-items", "{0} mag maximaal {1} bevatten", false); err != nil { - return - } - if err = ut.AddCardinal("max-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("max-items-item", "{0} items", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("max-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("max-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-items", fe.Field(), c) - - default: - t, err = ut.T("max-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eq", - translation: "{0} is niet gelijk aan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ne", - translation: "{0} mag niet gelijk zijn aan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lt-string", "{0} moet minder dan {1} lang zijn", false); err != nil { - return - } - - if err = ut.AddCardinal("lt-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lt-string-character", "{0} karakters", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-number", "{0} moet kleiner zijn dan {1}", false); err != nil { - return - } - - if err = ut.Add("lt-items", "{0} moet minder dan {1} bevatten", false); err != nil { - return - } - - if err = ut.AddCardinal("lt-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lt-items-item", "{0} items", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-datetime", "{0} moet kleiner zijn dan de huidige datum & tijd", false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lte-string", "{0} mag maximaal {1} lang zijn", false); err != nil { - return - } - - if err = ut.AddCardinal("lte-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lte-string-character", "{0} karakters", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-number", "{0} moet {1} of minder zijn", false); err != nil { - return - } - - if err = ut.Add("lte-items", "{0} mag maximaal {1} bevatten", false); err != nil { - return - } - - if err = ut.AddCardinal("lte-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lte-items-item", "{0} items", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-datetime", "{0} moet kleiner dan of gelijk aan de huidige datum & tijd zijn", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gt-string", "{0} moet langer dan {1} zijn", false); err != nil { - return - } - - if err = ut.AddCardinal("gt-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gt-string-character", "{0} karakters", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-number", "{0} moet groter zijn dan {1}", false); err != nil { - return - } - - if err = ut.Add("gt-items", "{0} moet meer dan {1} bevatten", false); err != nil { - return - } - - if err = ut.AddCardinal("gt-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gt-items-item", "{0} items", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-datetime", "{0} moet groter zijn dan de huidige datum & tijd", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gte-string", "{0} moet tenminste {1} lang zijn", false); err != nil { - return - } - - if err = ut.AddCardinal("gte-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gte-string-character", "{0} karakters", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-number", "{0} moet {1} of groter zijn", false); err != nil { - return - } - - if err = ut.Add("gte-items", "{0} moet tenminste {1} bevatten", false); err != nil { - return - } - - if err = ut.AddCardinal("gte-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gte-items-item", "{0} items", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-datetime", "{0} moet groter dan of gelijk zijn aan de huidige datum & tijd", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqfield", - translation: "{0} moet gelijk zijn aan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqcsfield", - translation: "{0} moet gelijk zijn aan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "necsfield", - translation: "{0} mag niet gelijk zijn aan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtcsfield", - translation: "{0} moet groter zijn dan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtecsfield", - translation: "{0} moet groter dan of gelijk aan {1} zijn", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltcsfield", - translation: "{0} moet kleiner zijn dan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltecsfield", - translation: "{0} moet kleiner dan of gelijk aan {1} zijn", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "nefield", - translation: "{0} mag niet gelijk zijn aan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtfield", - translation: "{0} moet groter zijn dan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtefield", - translation: "{0} moet groter dan of gelijk aan {1} zijn", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltfield", - translation: "{0} moet kleiner zijn dan {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltefield", - translation: "{0} moet kleiner dan of gelijk aan {1} zijn", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "alpha", - translation: "{0} mag alleen alfabetische karakters bevatten", - override: false, - }, - { - tag: "alphanum", - translation: "{0} mag alleen alfanumerieke karakters bevatten", - override: false, - }, - { - tag: "numeric", - translation: "{0} moet een geldige numerieke waarde zijn", - override: false, - }, - { - tag: "number", - translation: "{0} moet een geldig getal zijn", - override: false, - }, - { - tag: "hexadecimal", - translation: "{0} moet een geldig hexadecimaal getal zijn", - override: false, - }, - { - tag: "hexcolor", - translation: "{0} moet een geldige HEX kleur zijn", - override: false, - }, - { - tag: "rgb", - translation: "{0} moet een geldige RGB kleur zijn", - override: false, - }, - { - tag: "rgba", - translation: "{0} moet een geldige RGBA kleur zijn", - override: false, - }, - { - tag: "hsl", - translation: "{0} moet een geldige HSL kleur zijn", - override: false, - }, - { - tag: "hsla", - translation: "{0} moet een geldige HSLA kleur zijn", - override: false, - }, - { - tag: "email", - translation: "{0} moet een geldig email adres zijn", - override: false, - }, - { - tag: "url", - translation: "{0} moet een geldige URL zijn", - override: false, - }, - { - tag: "uri", - translation: "{0} moet een geldige URI zijn", - override: false, - }, - { - tag: "base64", - translation: "{0} moet een geldige Base64 string zijn", - override: false, - }, - { - tag: "contains", - translation: "{0} moet de tekst '{1}' bevatten", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "containsany", - translation: "{0} moet tenminste een van de volgende karakters bevatten '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludes", - translation: "{0} mag niet de tekst '{1}' bevatten", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesall", - translation: "{0} mag niet een van de volgende karakters bevatten '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesrune", - translation: "{0} mag niet het volgende bevatten '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "isbn", - translation: "{0} moet een geldig ISBN nummer zijn", - override: false, - }, - { - tag: "isbn10", - translation: "{0} moet een geldig ISBN-10 nummer zijn", - override: false, - }, - { - tag: "isbn13", - translation: "{0} moet een geldig ISBN-13 nummer zijn", - override: false, - }, - { - tag: "uuid", - translation: "{0} moet een geldige UUID zijn", - override: false, - }, - { - tag: "uuid3", - translation: "{0} moet een geldige versie 3 UUID zijn", - override: false, - }, - { - tag: "uuid4", - translation: "{0} moet een geldige versie 4 UUID zijn", - override: false, - }, - { - tag: "uuid5", - translation: "{0} moet een geldige versie 5 UUID zijn", - override: false, - }, - { - tag: "ascii", - translation: "{0} mag alleen ascii karakters bevatten", - override: false, - }, - { - tag: "printascii", - translation: "{0} mag alleen afdrukbare ascii karakters bevatten", - override: false, - }, - { - tag: "multibyte", - translation: "{0} moet multibyte karakters bevatten", - override: false, - }, - { - tag: "datauri", - translation: "{0} moet een geldige Data URI bevatten", - override: false, - }, - { - tag: "latitude", - translation: "{0} moet geldige breedtegraadcoördinaten bevatten", - override: false, - }, - { - tag: "longitude", - translation: "{0} moet geldige lengtegraadcoördinaten bevatten", - override: false, - }, - { - tag: "ssn", - translation: "{0} moet een geldig SSN nummer zijn", - override: false, - }, - { - tag: "ipv4", - translation: "{0} moet een geldig IPv4 adres zijn", - override: false, - }, - { - tag: "ipv6", - translation: "{0} moet een geldig IPv6 adres zijn", - override: false, - }, - { - tag: "ip", - translation: "{0} moet een geldig IP adres zijn", - override: false, - }, - { - tag: "cidr", - translation: "{0} moet een geldige CIDR notatie bevatten", - override: false, - }, - { - tag: "cidrv4", - translation: "{0} moet een geldige CIDR notatie voor een IPv4 adres bevatten", - override: false, - }, - { - tag: "cidrv6", - translation: "{0} moet een geldige CIDR notatie voor een IPv6 adres bevatten", - override: false, - }, - { - tag: "tcp_addr", - translation: "{0} moet een geldig TCP adres zijn", - override: false, - }, - { - tag: "tcp4_addr", - translation: "{0} moet een geldig IPv4 TCP adres zijn", - override: false, - }, - { - tag: "tcp6_addr", - translation: "{0} moet een geldig IPv6 TCP adres zijn", - override: false, - }, - { - tag: "udp_addr", - translation: "{0} moet een geldig UDP adres zijn", - override: false, - }, - { - tag: "udp4_addr", - translation: "{0} moet een geldig IPv4 UDP adres zijn", - override: false, - }, - { - tag: "udp6_addr", - translation: "{0} moet een geldig IPv6 UDP adres zijn", - override: false, - }, - { - tag: "ip_addr", - translation: "{0} moet een oplosbaar IP adres zijn", - override: false, - }, - { - tag: "ip4_addr", - translation: "{0} moet een oplosbaar IPv4 adres zijn", - override: false, - }, - { - tag: "ip6_addr", - translation: "{0} moet een oplosbaar IPv6 adres zijn", - override: false, - }, - { - tag: "unix_addr", - translation: "{0} moet een oplosbaar UNIX adres zijn", - override: false, - }, - { - tag: "mac", - translation: "{0} moet een geldig MAC adres bevatten", - override: false, - }, - { - tag: "iscolor", - translation: "{0} moet een geldige kleur zijn", - override: false, - }, - { - tag: "oneof", - translation: "{0} moet een van de volgende zijn [{1}]", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - s, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - return s - }, - }, - } - - for _, t := range translations { - - if t.customTransFunc != nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, t.customTransFunc) - - } else if t.customTransFunc != nil && t.customRegisFunc == nil { - - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), t.customTransFunc) - - } else if t.customTransFunc == nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, translateFunc) - - } else { - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), translateFunc) - } - - if err != nil { - return - } - } - - return -} - -func registrationFunc(tag string, translation string, override bool) validator.RegisterTranslationsFunc { - - return func(ut ut.Translator) (err error) { - - if err = ut.Add(tag, translation, override); err != nil { - return - } - - return - - } - -} - -func translateFunc(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t -} diff --git a/go-playground/validator/v10/translations/nl/nl_test.go b/go-playground/validator/v10/translations/nl/nl_test.go deleted file mode 100644 index 2f559b6..0000000 --- a/go-playground/validator/v10/translations/nl/nl_test.go +++ /dev/null @@ -1,634 +0,0 @@ -package nl - -import ( - "testing" - "time" - - . "git.ningdatech.com/ningda/gin_valid/go-playground/assert/v2" - english "git.ningdatech.com/ningda/gin_valid/go-playground/locales/en" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -func TestTranslations(t *testing.T) { - - eng := english.New() - uni := ut.New(eng, eng) - trans, _ := uni.GetTranslator("en") - - validate := validator.New() - - err := RegisterDefaultTranslations(validate, trans) - Equal(t, err, nil) - - type Inner struct { - EqCSFieldString string - NeCSFieldString string - GtCSFieldString string - GteCSFieldString string - LtCSFieldString string - LteCSFieldString string - } - - type Test struct { - Inner Inner - RequiredString string `validate:"required"` - RequiredNumber int `validate:"required"` - RequiredMultiple []string `validate:"required"` - LenString string `validate:"len=1"` - LenNumber float64 `validate:"len=1113.00"` - LenMultiple []string `validate:"len=7"` - MinString string `validate:"min=1"` - MinNumber float64 `validate:"min=1113.00"` - MinMultiple []string `validate:"min=7"` - MaxString string `validate:"max=3"` - MaxNumber float64 `validate:"max=1113.00"` - MaxMultiple []string `validate:"max=7"` - EqString string `validate:"eq=3"` - EqNumber float64 `validate:"eq=2.33"` - EqMultiple []string `validate:"eq=7"` - NeString string `validate:"ne="` - NeNumber float64 `validate:"ne=0.00"` - NeMultiple []string `validate:"ne=0"` - LtString string `validate:"lt=3"` - LtNumber float64 `validate:"lt=5.56"` - LtMultiple []string `validate:"lt=2"` - LtTime time.Time `validate:"lt"` - LteString string `validate:"lte=3"` - LteNumber float64 `validate:"lte=5.56"` - LteMultiple []string `validate:"lte=2"` - LteTime time.Time `validate:"lte"` - GtString string `validate:"gt=3"` - GtNumber float64 `validate:"gt=5.56"` - GtMultiple []string `validate:"gt=2"` - GtTime time.Time `validate:"gt"` - GteString string `validate:"gte=3"` - GteNumber float64 `validate:"gte=5.56"` - GteMultiple []string `validate:"gte=2"` - GteTime time.Time `validate:"gte"` - EqFieldString string `validate:"eqfield=MaxString"` - EqCSFieldString string `validate:"eqcsfield=Inner.EqCSFieldString"` - NeCSFieldString string `validate:"necsfield=Inner.NeCSFieldString"` - GtCSFieldString string `validate:"gtcsfield=Inner.GtCSFieldString"` - GteCSFieldString string `validate:"gtecsfield=Inner.GteCSFieldString"` - LtCSFieldString string `validate:"ltcsfield=Inner.LtCSFieldString"` - LteCSFieldString string `validate:"ltecsfield=Inner.LteCSFieldString"` - NeFieldString string `validate:"nefield=EqFieldString"` - GtFieldString string `validate:"gtfield=MaxString"` - GteFieldString string `validate:"gtefield=MaxString"` - LtFieldString string `validate:"ltfield=MaxString"` - LteFieldString string `validate:"ltefield=MaxString"` - AlphaString string `validate:"alpha"` - AlphanumString string `validate:"alphanum"` - NumericString string `validate:"numeric"` - NumberString string `validate:"number"` - HexadecimalString string `validate:"hexadecimal"` - HexColorString string `validate:"hexcolor"` - RGBColorString string `validate:"rgb"` - RGBAColorString string `validate:"rgba"` - HSLColorString string `validate:"hsl"` - HSLAColorString string `validate:"hsla"` - Email string `validate:"email"` - URL string `validate:"url"` - URI string `validate:"uri"` - Base64 string `validate:"base64"` - Contains string `validate:"contains=purpose"` - ContainsAny string `validate:"containsany=!@#$"` - Excludes string `validate:"excludes=text"` - ExcludesAll string `validate:"excludesall=!@#$"` - ExcludesRune string `validate:"excludesrune=☻"` - ISBN string `validate:"isbn"` - ISBN10 string `validate:"isbn10"` - ISBN13 string `validate:"isbn13"` - UUID string `validate:"uuid"` - UUID3 string `validate:"uuid3"` - UUID4 string `validate:"uuid4"` - UUID5 string `validate:"uuid5"` - ASCII string `validate:"ascii"` - PrintableASCII string `validate:"printascii"` - MultiByte string `validate:"multibyte"` - DataURI string `validate:"datauri"` - Latitude string `validate:"latitude"` - Longitude string `validate:"longitude"` - SSN string `validate:"ssn"` - IP string `validate:"ip"` - IPv4 string `validate:"ipv4"` - IPv6 string `validate:"ipv6"` - CIDR string `validate:"cidr"` - CIDRv4 string `validate:"cidrv4"` - CIDRv6 string `validate:"cidrv6"` - TCPAddr string `validate:"tcp_addr"` - TCPAddrv4 string `validate:"tcp4_addr"` - TCPAddrv6 string `validate:"tcp6_addr"` - UDPAddr string `validate:"udp_addr"` - UDPAddrv4 string `validate:"udp4_addr"` - UDPAddrv6 string `validate:"udp6_addr"` - IPAddr string `validate:"ip_addr"` - IPAddrv4 string `validate:"ip4_addr"` - IPAddrv6 string `validate:"ip6_addr"` - UinxAddr string `validate:"unix_addr"` // can't fail from within Go's net package currently, but maybe in the future - MAC string `validate:"mac"` - IsColor string `validate:"iscolor"` - StrPtrMinLen *string `validate:"min=10"` - StrPtrMaxLen *string `validate:"max=1"` - StrPtrLen *string `validate:"len=2"` - StrPtrLt *string `validate:"lt=1"` - StrPtrLte *string `validate:"lte=1"` - StrPtrGt *string `validate:"gt=10"` - StrPtrGte *string `validate:"gte=10"` - OneOfString string `validate:"oneof=red green"` - OneOfInt int `validate:"oneof=5 63"` - } - - var test Test - - test.Inner.EqCSFieldString = "1234" - test.Inner.GtCSFieldString = "1234" - test.Inner.GteCSFieldString = "1234" - - test.MaxString = "1234" - test.MaxNumber = 2000 - test.MaxMultiple = make([]string, 9) - - test.LtString = "1234" - test.LtNumber = 6 - test.LtMultiple = make([]string, 3) - test.LtTime = time.Now().Add(time.Hour * 24) - - test.LteString = "1234" - test.LteNumber = 6 - test.LteMultiple = make([]string, 3) - test.LteTime = time.Now().Add(time.Hour * 24) - - test.LtFieldString = "12345" - test.LteFieldString = "12345" - - test.LtCSFieldString = "1234" - test.LteCSFieldString = "1234" - - test.AlphaString = "abc3" - test.AlphanumString = "abc3!" - test.NumericString = "12E.00" - test.NumberString = "12E" - - test.Excludes = "this is some test text" - test.ExcludesAll = "This is Great!" - test.ExcludesRune = "Love it ☻" - - test.ASCII = "カタカナ" - test.PrintableASCII = "カタカナ" - - test.MultiByte = "1234feerf" - - s := "toolong" - test.StrPtrMaxLen = &s - test.StrPtrLen = &s - - err = validate.Struct(test) - NotEqual(t, err, nil) - - errs, ok := err.(validator.ValidationErrors) - Equal(t, ok, true) - - tests := []struct { - ns string - expected string - }{ - { - ns: "Test.IsColor", - expected: "IsColor moet een geldige kleur zijn", - }, - { - ns: "Test.MAC", - expected: "MAC moet een geldig MAC adres bevatten", - }, - { - ns: "Test.IPAddr", - expected: "IPAddr moet een oplosbaar IP adres zijn", - }, - { - ns: "Test.IPAddrv4", - expected: "IPAddrv4 moet een oplosbaar IPv4 adres zijn", - }, - { - ns: "Test.IPAddrv6", - expected: "IPAddrv6 moet een oplosbaar IPv6 adres zijn", - }, - { - ns: "Test.UDPAddr", - expected: "UDPAddr moet een geldig UDP adres zijn", - }, - { - ns: "Test.UDPAddrv4", - expected: "UDPAddrv4 moet een geldig IPv4 UDP adres zijn", - }, - { - ns: "Test.UDPAddrv6", - expected: "UDPAddrv6 moet een geldig IPv6 UDP adres zijn", - }, - { - ns: "Test.TCPAddr", - expected: "TCPAddr moet een geldig TCP adres zijn", - }, - { - ns: "Test.TCPAddrv4", - expected: "TCPAddrv4 moet een geldig IPv4 TCP adres zijn", - }, - { - ns: "Test.TCPAddrv6", - expected: "TCPAddrv6 moet een geldig IPv6 TCP adres zijn", - }, - { - ns: "Test.CIDR", - expected: "CIDR moet een geldige CIDR notatie bevatten", - }, - { - ns: "Test.CIDRv4", - expected: "CIDRv4 moet een geldige CIDR notatie voor een IPv4 adres bevatten", - }, - { - ns: "Test.CIDRv6", - expected: "CIDRv6 moet een geldige CIDR notatie voor een IPv6 adres bevatten", - }, - { - ns: "Test.SSN", - expected: "SSN moet een geldig SSN nummer zijn", - }, - { - ns: "Test.IP", - expected: "IP moet een geldig IP adres zijn", - }, - { - ns: "Test.IPv4", - expected: "IPv4 moet een geldig IPv4 adres zijn", - }, - { - ns: "Test.IPv6", - expected: "IPv6 moet een geldig IPv6 adres zijn", - }, - { - ns: "Test.DataURI", - expected: "DataURI moet een geldige Data URI bevatten", - }, - { - ns: "Test.Latitude", - expected: "Latitude moet geldige breedtegraadcoördinaten bevatten", - }, - { - ns: "Test.Longitude", - expected: "Longitude moet geldige lengtegraadcoördinaten bevatten", - }, - { - ns: "Test.MultiByte", - expected: "MultiByte moet multibyte karakters bevatten", - }, - { - ns: "Test.ASCII", - expected: "ASCII mag alleen ascii karakters bevatten", - }, - { - ns: "Test.PrintableASCII", - expected: "PrintableASCII mag alleen afdrukbare ascii karakters bevatten", - }, - { - ns: "Test.UUID", - expected: "UUID moet een geldige UUID zijn", - }, - { - ns: "Test.UUID3", - expected: "UUID3 moet een geldige versie 3 UUID zijn", - }, - { - ns: "Test.UUID4", - expected: "UUID4 moet een geldige versie 4 UUID zijn", - }, - { - ns: "Test.UUID5", - expected: "UUID5 moet een geldige versie 5 UUID zijn", - }, - { - ns: "Test.ISBN", - expected: "ISBN moet een geldig ISBN nummer zijn", - }, - { - ns: "Test.ISBN10", - expected: "ISBN10 moet een geldig ISBN-10 nummer zijn", - }, - { - ns: "Test.ISBN13", - expected: "ISBN13 moet een geldig ISBN-13 nummer zijn", - }, - { - ns: "Test.Excludes", - expected: "Excludes mag niet de tekst 'text' bevatten", - }, - { - ns: "Test.ExcludesAll", - expected: "ExcludesAll mag niet een van de volgende karakters bevatten '!@#$'", - }, - { - ns: "Test.ExcludesRune", - expected: "ExcludesRune mag niet het volgende bevatten '☻'", - }, - { - ns: "Test.ContainsAny", - expected: "ContainsAny moet tenminste een van de volgende karakters bevatten '!@#$'", - }, - { - ns: "Test.Contains", - expected: "Contains moet de tekst 'purpose' bevatten", - }, - { - ns: "Test.Base64", - expected: "Base64 moet een geldige Base64 string zijn", - }, - { - ns: "Test.Email", - expected: "Email moet een geldig email adres zijn", - }, - { - ns: "Test.URL", - expected: "URL moet een geldige URL zijn", - }, - { - ns: "Test.URI", - expected: "URI moet een geldige URI zijn", - }, - { - ns: "Test.RGBColorString", - expected: "RGBColorString moet een geldige RGB kleur zijn", - }, - { - ns: "Test.RGBAColorString", - expected: "RGBAColorString moet een geldige RGBA kleur zijn", - }, - { - ns: "Test.HSLColorString", - expected: "HSLColorString moet een geldige HSL kleur zijn", - }, - { - ns: "Test.HSLAColorString", - expected: "HSLAColorString moet een geldige HSLA kleur zijn", - }, - { - ns: "Test.HexadecimalString", - expected: "HexadecimalString moet een geldig hexadecimaal getal zijn", - }, - { - ns: "Test.HexColorString", - expected: "HexColorString moet een geldige HEX kleur zijn", - }, - { - ns: "Test.NumberString", - expected: "NumberString moet een geldig getal zijn", - }, - { - ns: "Test.NumericString", - expected: "NumericString moet een geldige numerieke waarde zijn", - }, - { - ns: "Test.AlphanumString", - expected: "AlphanumString mag alleen alfanumerieke karakters bevatten", - }, - { - ns: "Test.AlphaString", - expected: "AlphaString mag alleen alfabetische karakters bevatten", - }, - { - ns: "Test.LtFieldString", - expected: "LtFieldString moet kleiner zijn dan MaxString", - }, - { - ns: "Test.LteFieldString", - expected: "LteFieldString moet kleiner dan of gelijk aan MaxString zijn", - }, - { - ns: "Test.GtFieldString", - expected: "GtFieldString moet groter zijn dan MaxString", - }, - { - ns: "Test.GteFieldString", - expected: "GteFieldString moet groter dan of gelijk aan MaxString zijn", - }, - { - ns: "Test.NeFieldString", - expected: "NeFieldString mag niet gelijk zijn aan EqFieldString", - }, - { - ns: "Test.LtCSFieldString", - expected: "LtCSFieldString moet kleiner zijn dan Inner.LtCSFieldString", - }, - { - ns: "Test.LteCSFieldString", - expected: "LteCSFieldString moet kleiner dan of gelijk aan Inner.LteCSFieldString zijn", - }, - { - ns: "Test.GtCSFieldString", - expected: "GtCSFieldString moet groter zijn dan Inner.GtCSFieldString", - }, - { - ns: "Test.GteCSFieldString", - expected: "GteCSFieldString moet groter dan of gelijk aan Inner.GteCSFieldString zijn", - }, - { - ns: "Test.NeCSFieldString", - expected: "NeCSFieldString mag niet gelijk zijn aan Inner.NeCSFieldString", - }, - { - ns: "Test.EqCSFieldString", - expected: "EqCSFieldString moet gelijk zijn aan Inner.EqCSFieldString", - }, - { - ns: "Test.EqFieldString", - expected: "EqFieldString moet gelijk zijn aan MaxString", - }, - { - ns: "Test.GteString", - expected: "GteString moet tenminste 3 karakters lang zijn", - }, - { - ns: "Test.GteNumber", - expected: "GteNumber moet 5.56 of groter zijn", - }, - { - ns: "Test.GteMultiple", - expected: "GteMultiple moet tenminste 2 items bevatten", - }, - { - ns: "Test.GteTime", - expected: "GteTime moet groter dan of gelijk zijn aan de huidige datum & tijd", - }, - { - ns: "Test.GtString", - expected: "GtString moet langer dan 3 karakters zijn", - }, - { - ns: "Test.GtNumber", - expected: "GtNumber moet groter zijn dan 5.56", - }, - { - ns: "Test.GtMultiple", - expected: "GtMultiple moet meer dan 2 items bevatten", - }, - { - ns: "Test.GtTime", - expected: "GtTime moet groter zijn dan de huidige datum & tijd", - }, - { - ns: "Test.LteString", - expected: "LteString mag maximaal 3 karakters lang zijn", - }, - { - ns: "Test.LteNumber", - expected: "LteNumber moet 5.56 of minder zijn", - }, - { - ns: "Test.LteMultiple", - expected: "LteMultiple mag maximaal 2 items bevatten", - }, - { - ns: "Test.LteTime", - expected: "LteTime moet kleiner dan of gelijk aan de huidige datum & tijd zijn", - }, - { - ns: "Test.LtString", - expected: "LtString moet minder dan 3 karakters lang zijn", - }, - { - ns: "Test.LtNumber", - expected: "LtNumber moet kleiner zijn dan 5.56", - }, - { - ns: "Test.LtMultiple", - expected: "LtMultiple moet minder dan 2 items bevatten", - }, - { - ns: "Test.LtTime", - expected: "LtTime moet kleiner zijn dan de huidige datum & tijd", - }, - { - ns: "Test.NeString", - expected: "NeString mag niet gelijk zijn aan ", - }, - { - ns: "Test.NeNumber", - expected: "NeNumber mag niet gelijk zijn aan 0.00", - }, - { - ns: "Test.NeMultiple", - expected: "NeMultiple mag niet gelijk zijn aan 0", - }, - { - ns: "Test.EqString", - expected: "EqString is niet gelijk aan 3", - }, - { - ns: "Test.EqNumber", - expected: "EqNumber is niet gelijk aan 2.33", - }, - { - ns: "Test.EqMultiple", - expected: "EqMultiple is niet gelijk aan 7", - }, - { - ns: "Test.MaxString", - expected: "MaxString mag maximaal 3 karakters lang zijn", - }, - { - ns: "Test.MaxNumber", - expected: "MaxNumber moet 1,113.00 of kleiner zijn", - }, - { - ns: "Test.MaxMultiple", - expected: "MaxMultiple mag maximaal 7 items bevatten", - }, - { - ns: "Test.MinString", - expected: "MinString moet tenminste 1 karakter lang zijn", - }, - { - ns: "Test.MinNumber", - expected: "MinNumber moet 1,113.00 of groter zijn", - }, - { - ns: "Test.MinMultiple", - expected: "MinMultiple moet tenminste 7 items bevatten", - }, - { - ns: "Test.LenString", - expected: "LenString moet 1 karakter lang zijn", - }, - { - ns: "Test.LenNumber", - expected: "LenNumber moet gelijk zijn aan 1,113.00", - }, - { - ns: "Test.LenMultiple", - expected: "LenMultiple moet 7 items bevatten", - }, - { - ns: "Test.RequiredString", - expected: "RequiredString is een verplicht veld", - }, - { - ns: "Test.RequiredNumber", - expected: "RequiredNumber is een verplicht veld", - }, - { - ns: "Test.RequiredMultiple", - expected: "RequiredMultiple is een verplicht veld", - }, - { - ns: "Test.StrPtrMinLen", - expected: "StrPtrMinLen moet tenminste 10 karakters lang zijn", - }, - { - ns: "Test.StrPtrMaxLen", - expected: "StrPtrMaxLen mag maximaal 1 karakter lang zijn", - }, - { - ns: "Test.StrPtrLen", - expected: "StrPtrLen moet 2 karakters lang zijn", - }, - { - ns: "Test.StrPtrLt", - expected: "StrPtrLt moet minder dan 1 karakter lang zijn", - }, - { - ns: "Test.StrPtrLte", - expected: "StrPtrLte mag maximaal 1 karakter lang zijn", - }, - { - ns: "Test.StrPtrGt", - expected: "StrPtrGt moet langer dan 10 karakters zijn", - }, - { - ns: "Test.StrPtrGte", - expected: "StrPtrGte moet tenminste 10 karakters lang zijn", - }, - { - ns: "Test.OneOfString", - expected: "OneOfString moet een van de volgende zijn [red green]", - }, - { - ns: "Test.OneOfInt", - expected: "OneOfInt moet een van de volgende zijn [5 63]", - }, - } - - for _, tt := range tests { - - var fe validator.FieldError - - for _, e := range errs { - if tt.ns == e.Namespace() { - fe = e - break - } - } - - NotEqual(t, fe, nil) - Equal(t, tt.expected, fe.Translate(trans)) - } - -} diff --git a/go-playground/validator/v10/translations/pt/pt.go b/go-playground/validator/v10/translations/pt/pt.go deleted file mode 100644 index 91399a7..0000000 --- a/go-playground/validator/v10/translations/pt/pt.go +++ /dev/null @@ -1,1405 +0,0 @@ -package pt - -import ( - "fmt" - "log" - "reflect" - "strconv" - "strings" - "time" - - "git.ningdatech.com/ningda/gin_valid/go-playground/locales" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -// RegisterDefaultTranslations registers a set of default translations -// for all built in tag's in validator; you may add your own as desired. -func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (err error) { - - translations := []struct { - tag string - translation string - override bool - customRegisFunc validator.RegisterTranslationsFunc - customTransFunc validator.TranslationFunc - }{ - { - tag: "required", - translation: "{0} é obrigatório", - override: false, - }, - { - tag: "len", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("len-string", "{0} deve ter {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("len-string-character", "{0} caractere", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("len-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("len-number", "{0} deve ser igual a {1}", false); err != nil { - return - } - - if err = ut.Add("len-items", "{0} deve conter {1}", false); err != nil { - return - } - if err = ut.AddCardinal("len-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("len-items-item", "{0} items", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("len-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("len-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-items", fe.Field(), c) - - default: - t, err = ut.T("len-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "min", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("min-string", "{0} deve ter pelo menos {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("min-string-character", "{0} caractere", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("min-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("min-number", "{0} deve ser {1} ou superior", false); err != nil { - return - } - - if err = ut.Add("min-items", "{0} deve conter pelo menos {1}", false); err != nil { - return - } - if err = ut.AddCardinal("min-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("min-items-item", "{0} items", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("min-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("min-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-items", fe.Field(), c) - - default: - t, err = ut.T("min-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "max", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("max-string", "{0} deve ter no máximo {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("max-string-character", "{0} caractere", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("max-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("max-number", "{0} deve ser {1} ou menos", false); err != nil { - return - } - - if err = ut.Add("max-items", "{0} deve conter no máximo {1}", false); err != nil { - return - } - if err = ut.AddCardinal("max-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("max-items-item", "{0} items", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("max-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("max-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-items", fe.Field(), c) - - default: - t, err = ut.T("max-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eq", - translation: "{0} não é igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ne", - translation: "{0} não deve ser igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lt-string", "{0} deve ter menos de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lt-string-character", "{0} caractere", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lt-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-number", "{0} deve ser menor que {1}", false); err != nil { - return - } - - if err = ut.Add("lt-items", "{0} deve conter menos de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lt-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lt-items-item", "{0} items", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-datetime", "{0} deve ser anterior à data / hora atual", false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lte-string", "{0} deve ter no máximo {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lte-string-character", "{0} caractere", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lte-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-number", "{0} deve ser menor ou igual a {1}", false); err != nil { - return - } - - if err = ut.Add("lte-items", "{0} deve conter no máximo {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lte-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lte-items-item", "{0} items", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-datetime", "{0} deve ser anterior ou igual à data/hora atual", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gt-string", "{0} deve conter mais de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gt-string-character", "{0} caractere", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gt-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-number", "{0} deve ser maior que {1}", false); err != nil { - return - } - - if err = ut.Add("gt-items", "{0} deve conter mais de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gt-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gt-items-item", "{0} items", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-datetime", "{0} deve ser posterior à data/hora atual", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gte-string", "{0} deve ter pelo menos {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gte-string-character", "{0} caractere", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gte-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-number", "{0} deve ser maior ou igual a {1}", false); err != nil { - return - } - - if err = ut.Add("gte-items", "{0} deve conter pelo menos {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gte-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gte-items-item", "{0} items", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-datetime", "{0} deve ser posterior ou igual à data/hora atual", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqfield", - translation: "{0} deve ser igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqcsfield", - translation: "{0} deve ser igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "necsfield", - translation: "{0} não deve ser igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtcsfield", - translation: "{0} deve ser maior que {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtecsfield", - translation: "{0} deve ser maior ou igual que {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltcsfield", - translation: "{0} deve ser menor que {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltecsfield", - translation: "{0} deve ser menor ou igual que {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "nefield", - translation: "{0} não deve ser igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtfield", - translation: "{0} deve ser maior que {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtefield", - translation: "{0} deve ser maior ou igual que {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltfield", - translation: "{0} deve ser menor que {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltefield", - translation: "{0} deve ser menor ou igual que {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "alpha", - translation: "{0} deve conter apenas caracteres alfabéticos", - override: false, - }, - { - tag: "alphanum", - translation: "{0} deve conter apenas caracteres alfanuméricos", - override: false, - }, - { - tag: "numeric", - translation: "{0} deve ser um valor numérico válido", - override: false, - }, - { - tag: "number", - translation: "{0} deve ser um número válido", - override: false, - }, - { - tag: "hexadecimal", - translation: "{0} deve ser um hexadecimal válido", - override: false, - }, - { - tag: "hexcolor", - translation: "{0} deve ser uma cor HEX válida", - override: false, - }, - { - tag: "rgb", - translation: "{0} deve ser uma cor RGB válida", - override: false, - }, - { - tag: "rgba", - translation: "{0} deve ser uma cor RGBA válida", - override: false, - }, - { - tag: "hsl", - translation: "{0} deve ser uma cor HSL válida", - override: false, - }, - { - tag: "hsla", - translation: "{0} deve ser uma cor HSLA válida", - override: false, - }, - { - tag: "e164", - translation: "{0} deve ser um número de telefone válido no formato E.164", - override: false, - }, - { - tag: "email", - translation: "{0} deve ser um endereço de e-mail válido", - override: false, - }, - { - tag: "url", - translation: "{0} deve ser um URL válido", - override: false, - }, - { - tag: "uri", - translation: "{0} deve ser um URI válido", - override: false, - }, - { - tag: "base64", - translation: "{0} deve ser uma string Base64 válida", - override: false, - }, - { - tag: "contains", - translation: "{0} deve conter o texto '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "containsany", - translation: "{0} deve conter pelo menos um dos seguintes caracteres '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludes", - translation: "{0} não deve conter o texto '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesall", - translation: "{0} não deve conter os seguintes caracteres '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesrune", - translation: "{0} não pode conter o seguinte '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "isbn", - translation: "{0} deve ser um número de ISBN válido", - override: false, - }, - { - tag: "isbn10", - translation: "{0} deve ser um número ISBN-10 válido", - override: false, - }, - { - tag: "isbn13", - translation: "{0} deve ser um número ISBN-13 válido", - override: false, - }, - { - tag: "uuid", - translation: "{0} deve ser um UUID válido", - override: false, - }, - { - tag: "uuid3", - translation: "{0} deve ser um UUID versão 3 válido", - override: false, - }, - { - tag: "uuid4", - translation: "{0} deve ser um UUID versão 4 válido", - override: false, - }, - { - tag: "uuid5", - translation: "{0} deve ser um UUID versão 5 válido", - override: false, - }, - { - tag: "ascii", - translation: "{0} deve conter apenas caracteres ascii", - override: false, - }, - { - tag: "printascii", - translation: "{0} deve conter apenas caracteres ascii imprimíveis", - override: false, - }, - { - tag: "multibyte", - translation: "{0} deve conter caracteres multibyte", - override: false, - }, - { - tag: "datauri", - translation: "{0} deve conter um Data URI válido", - override: false, - }, - { - tag: "latitude", - translation: "{0} deve conter uma coordenada de latitude válida", - override: false, - }, - { - tag: "longitude", - translation: "{0} deve conter uma coordenada de longitude válida", - override: false, - }, - { - tag: "ssn", - translation: "{0} deve ser um número SSN válido", - override: false, - }, - { - tag: "ipv4", - translation: "{0} deve ser um endereço IPv4 válido", - override: false, - }, - { - tag: "ipv6", - translation: "{0} deve ser um endereço IPv6 válido", - override: false, - }, - { - tag: "ip", - translation: "{0} deve ser um endereço IP válido", - override: false, - }, - { - tag: "cidr", - translation: "{0} não respeita a notação CIDR", - override: false, - }, - { - tag: "cidrv4", - translation: "{0} não respeita a notação CIDR para um endereço IPv4", - override: false, - }, - { - tag: "cidrv6", - translation: "{0} não respeita a notação CIDR para um endereço IPv6", - override: false, - }, - { - tag: "tcp_addr", - translation: "{0} deve ser um endereço TCP válido", - override: false, - }, - { - tag: "tcp4_addr", - translation: "{0} deve ser um endereço TCP IPv4 válido", - override: false, - }, - { - tag: "tcp6_addr", - translation: "{0} deve ser um endereço TCP IPv6 válido", - override: false, - }, - { - tag: "udp_addr", - translation: "{0} deve ser um endereço UDP válido", - override: false, - }, - { - tag: "udp4_addr", - translation: "{0} deve ser um endereço UDP IPv4 válido", - override: false, - }, - { - tag: "udp6_addr", - translation: "{0} deve ser um endereço UDP IPv6 válido", - override: false, - }, - { - tag: "ip_addr", - translation: "{0} deve ser um endereço IP resolvível", - override: false, - }, - { - tag: "ip4_addr", - translation: "{0} deve ser um endereço IPv4 resolvível", - override: false, - }, - { - tag: "ip6_addr", - translation: "{0} deve ser um endereço IPv6 resolvível", - override: false, - }, - { - tag: "unix_addr", - translation: "{0} deve ser um endereço UNIX resolvível", - override: false, - }, - { - tag: "mac", - translation: "{0} deve conter um endereço MAC válido", - override: false, - }, - { - tag: "unique", - translation: "{0} deve conter valores únicos", - override: false, - }, - { - tag: "iscolor", - translation: "{0} deve ser uma cor válida", - override: false, - }, - { - tag: "oneof", - translation: "{0} deve ser um de [{1}]", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - s, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - return s - }, - }, - { - tag: "json", - translation: "{0} deve ser uma string json válida", - override: false, - }, - { - tag: "lowercase", - translation: "{0} deve estar em minuscúlas", - override: false, - }, - { - tag: "uppercase", - translation: "{0} deve estar em maiúsculas", - override: false, - }, - { - tag: "datetime", - translation: "{0} não está no formato {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - } - - for _, t := range translations { - - if t.customTransFunc != nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, t.customTransFunc) - - } else if t.customTransFunc != nil && t.customRegisFunc == nil { - - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), t.customTransFunc) - - } else if t.customTransFunc == nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, translateFunc) - - } else { - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), translateFunc) - } - - if err != nil { - return - } - } - - return -} - -func registrationFunc(tag string, translation string, override bool) validator.RegisterTranslationsFunc { - - return func(ut ut.Translator) (err error) { - - if err = ut.Add(tag, translation, override); err != nil { - return - } - - return - - } - -} - -func translateFunc(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t -} diff --git a/go-playground/validator/v10/translations/pt/pt_test.go b/go-playground/validator/v10/translations/pt/pt_test.go deleted file mode 100644 index 9b180d8..0000000 --- a/go-playground/validator/v10/translations/pt/pt_test.go +++ /dev/null @@ -1,677 +0,0 @@ -package pt - -import ( - "testing" - "time" - - . "git.ningdatech.com/ningda/gin_valid/go-playground/assert/v2" - "git.ningdatech.com/ningda/gin_valid/go-playground/locales/pt" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -func TestTranslations(t *testing.T) { - - pt := pt.New() - uni := ut.New(pt, pt) - trans, _ := uni.GetTranslator("pt") - - validate := validator.New() - - err := RegisterDefaultTranslations(validate, trans) - Equal(t, err, nil) - - type Inner struct { - EqCSFieldString string - NeCSFieldString string - GtCSFieldString string - GteCSFieldString string - LtCSFieldString string - LteCSFieldString string - } - - type Test struct { - Inner Inner - RequiredString string `validate:"required"` - RequiredNumber int `validate:"required"` - RequiredMultiple []string `validate:"required"` - LenString string `validate:"len=1"` - LenNumber float64 `validate:"len=1113.00"` - LenMultiple []string `validate:"len=7"` - MinString string `validate:"min=1"` - MinNumber float64 `validate:"min=1113.00"` - MinMultiple []string `validate:"min=7"` - MaxString string `validate:"max=3"` - MaxNumber float64 `validate:"max=1113.00"` - MaxMultiple []string `validate:"max=7"` - EqString string `validate:"eq=3"` - EqNumber float64 `validate:"eq=2.33"` - EqMultiple []string `validate:"eq=7"` - NeString string `validate:"ne="` - NeNumber float64 `validate:"ne=0.00"` - NeMultiple []string `validate:"ne=0"` - LtString string `validate:"lt=3"` - LtNumber float64 `validate:"lt=5.56"` - LtMultiple []string `validate:"lt=2"` - LtTime time.Time `validate:"lt"` - LteString string `validate:"lte=3"` - LteNumber float64 `validate:"lte=5.56"` - LteMultiple []string `validate:"lte=2"` - LteTime time.Time `validate:"lte"` - GtString string `validate:"gt=3"` - GtNumber float64 `validate:"gt=5.56"` - GtMultiple []string `validate:"gt=2"` - GtTime time.Time `validate:"gt"` - GteString string `validate:"gte=3"` - GteNumber float64 `validate:"gte=5.56"` - GteMultiple []string `validate:"gte=2"` - GteTime time.Time `validate:"gte"` - EqFieldString string `validate:"eqfield=MaxString"` - EqCSFieldString string `validate:"eqcsfield=Inner.EqCSFieldString"` - NeCSFieldString string `validate:"necsfield=Inner.NeCSFieldString"` - GtCSFieldString string `validate:"gtcsfield=Inner.GtCSFieldString"` - GteCSFieldString string `validate:"gtecsfield=Inner.GteCSFieldString"` - LtCSFieldString string `validate:"ltcsfield=Inner.LtCSFieldString"` - LteCSFieldString string `validate:"ltecsfield=Inner.LteCSFieldString"` - NeFieldString string `validate:"nefield=EqFieldString"` - GtFieldString string `validate:"gtfield=MaxString"` - GteFieldString string `validate:"gtefield=MaxString"` - LtFieldString string `validate:"ltfield=MaxString"` - LteFieldString string `validate:"ltefield=MaxString"` - AlphaString string `validate:"alpha"` - AlphanumString string `validate:"alphanum"` - NumericString string `validate:"numeric"` - NumberString string `validate:"number"` - HexadecimalString string `validate:"hexadecimal"` - HexColorString string `validate:"hexcolor"` - RGBColorString string `validate:"rgb"` - RGBAColorString string `validate:"rgba"` - HSLColorString string `validate:"hsl"` - HSLAColorString string `validate:"hsla"` - Email string `validate:"email"` - URL string `validate:"url"` - URI string `validate:"uri"` - Base64 string `validate:"base64"` - Contains string `validate:"contains=purpose"` - ContainsAny string `validate:"containsany=!@#$"` - Excludes string `validate:"excludes=text"` - ExcludesAll string `validate:"excludesall=!@#$"` - ExcludesRune string `validate:"excludesrune=☻"` - ISBN string `validate:"isbn"` - ISBN10 string `validate:"isbn10"` - ISBN13 string `validate:"isbn13"` - UUID string `validate:"uuid"` - UUID3 string `validate:"uuid3"` - UUID4 string `validate:"uuid4"` - UUID5 string `validate:"uuid5"` - ASCII string `validate:"ascii"` - PrintableASCII string `validate:"printascii"` - MultiByte string `validate:"multibyte"` - DataURI string `validate:"datauri"` - Latitude string `validate:"latitude"` - Longitude string `validate:"longitude"` - SSN string `validate:"ssn"` - IP string `validate:"ip"` - IPv4 string `validate:"ipv4"` - IPv6 string `validate:"ipv6"` - CIDR string `validate:"cidr"` - CIDRv4 string `validate:"cidrv4"` - CIDRv6 string `validate:"cidrv6"` - TCPAddr string `validate:"tcp_addr"` - TCPAddrv4 string `validate:"tcp4_addr"` - TCPAddrv6 string `validate:"tcp6_addr"` - UDPAddr string `validate:"udp_addr"` - UDPAddrv4 string `validate:"udp4_addr"` - UDPAddrv6 string `validate:"udp6_addr"` - IPAddr string `validate:"ip_addr"` - IPAddrv4 string `validate:"ip4_addr"` - IPAddrv6 string `validate:"ip6_addr"` - UinxAddr string `validate:"unix_addr"` // can't fail from within Go's net package currently, but maybe in the future - MAC string `validate:"mac"` - IsColor string `validate:"iscolor"` - StrPtrMinLen *string `validate:"min=10"` - StrPtrMaxLen *string `validate:"max=1"` - StrPtrLen *string `validate:"len=2"` - StrPtrLt *string `validate:"lt=1"` - StrPtrLte *string `validate:"lte=1"` - StrPtrGt *string `validate:"gt=10"` - StrPtrGte *string `validate:"gte=10"` - OneOfString string `validate:"oneof=red green"` - OneOfInt int `validate:"oneof=5 63"` - UniqueSlice []string `validate:"unique"` - UniqueArray [3]string `validate:"unique"` - UniqueMap map[string]string `validate:"unique"` - JSONString string `validate:"json"` - LowercaseString string `validate:"lowercase"` - UppercaseString string `validate:"uppercase"` - Datetime string `validate:"datetime=2006-01-02"` - } - - var test Test - - test.Inner.EqCSFieldString = "1234" - test.Inner.GtCSFieldString = "1234" - test.Inner.GteCSFieldString = "1234" - - test.MaxString = "1234" - test.MaxNumber = 2000 - test.MaxMultiple = make([]string, 9) - - test.LtString = "1234" - test.LtNumber = 6 - test.LtMultiple = make([]string, 3) - test.LtTime = time.Now().Add(time.Hour * 24) - - test.LteString = "1234" - test.LteNumber = 6 - test.LteMultiple = make([]string, 3) - test.LteTime = time.Now().Add(time.Hour * 24) - - test.LtFieldString = "12345" - test.LteFieldString = "12345" - - test.LtCSFieldString = "1234" - test.LteCSFieldString = "1234" - - test.AlphaString = "abc3" - test.AlphanumString = "abc3!" - test.NumericString = "12E.00" - test.NumberString = "12E" - - test.Excludes = "this is some test text" - test.ExcludesAll = "This is Great!" - test.ExcludesRune = "Love it ☻" - - test.ASCII = "カタカナ" - test.PrintableASCII = "カタカナ" - - test.MultiByte = "1234feerf" - - test.LowercaseString = "ABCDEFG" - test.UppercaseString = "abcdefg" - - s := "toolong" - test.StrPtrMaxLen = &s - test.StrPtrLen = &s - - test.UniqueSlice = []string{"1234", "1234"} - test.UniqueMap = map[string]string{"key1": "1234", "key2": "1234"} - test.Datetime = "2008-Feb-01" - - err = validate.Struct(test) - NotEqual(t, err, nil) - - errs, ok := err.(validator.ValidationErrors) - Equal(t, ok, true) - - tests := []struct { - ns string - expected string - }{ - { - ns: "Test.IsColor", - expected: "IsColor deve ser uma cor válida", - }, - { - ns: "Test.MAC", - expected: "MAC deve conter um endereço MAC válido", - }, - { - ns: "Test.IPAddr", - expected: "IPAddr deve ser um endereço IP resolvível", - }, - { - ns: "Test.IPAddrv4", - expected: "IPAddrv4 deve ser um endereço IPv4 resolvível", - }, - { - ns: "Test.IPAddrv6", - expected: "IPAddrv6 deve ser um endereço IPv6 resolvível", - }, - { - ns: "Test.UDPAddr", - expected: "UDPAddr deve ser um endereço UDP válido", - }, - { - ns: "Test.UDPAddrv4", - expected: "UDPAddrv4 deve ser um endereço UDP IPv4 válido", - }, - { - ns: "Test.UDPAddrv6", - expected: "UDPAddrv6 deve ser um endereço UDP IPv6 válido", - }, - { - ns: "Test.TCPAddr", - expected: "TCPAddr deve ser um endereço TCP válido", - }, - { - ns: "Test.TCPAddrv4", - expected: "TCPAddrv4 deve ser um endereço TCP IPv4 válido", - }, - { - ns: "Test.TCPAddrv6", - expected: "TCPAddrv6 deve ser um endereço TCP IPv6 válido", - }, - { - ns: "Test.CIDR", - expected: "CIDR não respeita a notação CIDR", - }, - { - ns: "Test.CIDRv4", - expected: "CIDRv4 não respeita a notação CIDR para um endereço IPv4", - }, - { - ns: "Test.CIDRv6", - expected: "CIDRv6 não respeita a notação CIDR para um endereço IPv6", - }, - { - ns: "Test.SSN", - expected: "SSN deve ser um número SSN válido", - }, - { - ns: "Test.IP", - expected: "IP deve ser um endereço IP válido", - }, - { - ns: "Test.IPv4", - expected: "IPv4 deve ser um endereço IPv4 válido", - }, - { - ns: "Test.IPv6", - expected: "IPv6 deve ser um endereço IPv6 válido", - }, - { - ns: "Test.DataURI", - expected: "DataURI deve conter um Data URI válido", - }, - { - ns: "Test.Latitude", - expected: "Latitude deve conter uma coordenada de latitude válida", - }, - { - ns: "Test.Longitude", - expected: "Longitude deve conter uma coordenada de longitude válida", - }, - { - ns: "Test.MultiByte", - expected: "MultiByte deve conter caracteres multibyte", - }, - { - ns: "Test.ASCII", - expected: "ASCII deve conter apenas caracteres ascii", - }, - { - ns: "Test.PrintableASCII", - expected: "PrintableASCII deve conter apenas caracteres ascii imprimíveis", - }, - { - ns: "Test.UUID", - expected: "UUID deve ser um UUID válido", - }, - { - ns: "Test.UUID3", - expected: "UUID3 deve ser um UUID versão 3 válido", - }, - { - ns: "Test.UUID4", - expected: "UUID4 deve ser um UUID versão 4 válido", - }, - { - ns: "Test.UUID5", - expected: "UUID5 deve ser um UUID versão 5 válido", - }, - { - ns: "Test.ISBN", - expected: "ISBN deve ser um número de ISBN válido", - }, - { - ns: "Test.ISBN10", - expected: "ISBN10 deve ser um número ISBN-10 válido", - }, - { - ns: "Test.ISBN13", - expected: "ISBN13 deve ser um número ISBN-13 válido", - }, - { - ns: "Test.Excludes", - expected: "Excludes não deve conter o texto 'text'", - }, - { - ns: "Test.ExcludesAll", - expected: "ExcludesAll não deve conter os seguintes caracteres '!@#$'", - }, - { - ns: "Test.ExcludesRune", - expected: "ExcludesRune não pode conter o seguinte '☻'", - }, - { - ns: "Test.ContainsAny", - expected: "ContainsAny deve conter pelo menos um dos seguintes caracteres '!@#$'", - }, - { - ns: "Test.Contains", - expected: "Contains deve conter o texto 'purpose'", - }, - { - ns: "Test.Base64", - expected: "Base64 deve ser uma string Base64 válida", - }, - { - ns: "Test.Email", - expected: "Email deve ser um endereço de e-mail válido", - }, - { - ns: "Test.URL", - expected: "URL deve ser um URL válido", - }, - { - ns: "Test.URI", - expected: "URI deve ser um URI válido", - }, - { - ns: "Test.RGBColorString", - expected: "RGBColorString deve ser uma cor RGB válida", - }, - { - ns: "Test.RGBAColorString", - expected: "RGBAColorString deve ser uma cor RGBA válida", - }, - { - ns: "Test.HSLColorString", - expected: "HSLColorString deve ser uma cor HSL válida", - }, - { - ns: "Test.HSLAColorString", - expected: "HSLAColorString deve ser uma cor HSLA válida", - }, - { - ns: "Test.HexadecimalString", - expected: "HexadecimalString deve ser um hexadecimal válido", - }, - { - ns: "Test.HexColorString", - expected: "HexColorString deve ser uma cor HEX válida", - }, - { - ns: "Test.NumberString", - expected: "NumberString deve ser um número válido", - }, - { - ns: "Test.NumericString", - expected: "NumericString deve ser um valor numérico válido", - }, - { - ns: "Test.AlphanumString", - expected: "AlphanumString deve conter apenas caracteres alfanuméricos", - }, - { - ns: "Test.AlphaString", - expected: "AlphaString deve conter apenas caracteres alfabéticos", - }, - { - ns: "Test.LtFieldString", - expected: "LtFieldString deve ser menor que MaxString", - }, - { - ns: "Test.LteFieldString", - expected: "LteFieldString deve ser menor ou igual que MaxString", - }, - { - ns: "Test.GtFieldString", - expected: "GtFieldString deve ser maior que MaxString", - }, - { - ns: "Test.GteFieldString", - expected: "GteFieldString deve ser maior ou igual que MaxString", - }, - { - ns: "Test.NeFieldString", - expected: "NeFieldString não deve ser igual a EqFieldString", - }, - { - ns: "Test.LtCSFieldString", - expected: "LtCSFieldString deve ser menor que Inner.LtCSFieldString", - }, - { - ns: "Test.LteCSFieldString", - expected: "LteCSFieldString deve ser menor ou igual que Inner.LteCSFieldString", - }, - { - ns: "Test.GtCSFieldString", - expected: "GtCSFieldString deve ser maior que Inner.GtCSFieldString", - }, - { - ns: "Test.GteCSFieldString", - expected: "GteCSFieldString deve ser maior ou igual que Inner.GteCSFieldString", - }, - { - ns: "Test.NeCSFieldString", - expected: "NeCSFieldString não deve ser igual a Inner.NeCSFieldString", - }, - { - ns: "Test.EqCSFieldString", - expected: "EqCSFieldString deve ser igual a Inner.EqCSFieldString", - }, - { - ns: "Test.EqFieldString", - expected: "EqFieldString deve ser igual a MaxString", - }, - { - ns: "Test.GteString", - expected: "GteString deve ter pelo menos 3 caracteres", - }, - { - ns: "Test.GteNumber", - expected: "GteNumber deve ser maior ou igual a 5,56", - }, - { - ns: "Test.GteMultiple", - expected: "GteMultiple deve conter pelo menos 2 items", - }, - { - ns: "Test.GteTime", - expected: "GteTime deve ser posterior ou igual à data/hora atual", - }, - { - ns: "Test.GtString", - expected: "GtString deve conter mais de 3 caracteres", - }, - { - ns: "Test.GtNumber", - expected: "GtNumber deve ser maior que 5,56", - }, - { - ns: "Test.GtMultiple", - expected: "GtMultiple deve conter mais de 2 items", - }, - { - ns: "Test.GtTime", - expected: "GtTime deve ser posterior à data/hora atual", - }, - { - ns: "Test.LteString", - expected: "LteString deve ter no máximo 3 caracteres", - }, - { - ns: "Test.LteNumber", - expected: "LteNumber deve ser menor ou igual a 5,56", - }, - { - ns: "Test.LteMultiple", - expected: "LteMultiple deve conter no máximo 2 items", - }, - { - ns: "Test.LteTime", - expected: "LteTime deve ser anterior ou igual à data/hora atual", - }, - { - ns: "Test.LtString", - expected: "LtString deve ter menos de 3 caracteres", - }, - { - ns: "Test.LtNumber", - expected: "LtNumber deve ser menor que 5,56", - }, - { - ns: "Test.LtMultiple", - expected: "LtMultiple deve conter menos de 2 items", - }, - { - ns: "Test.LtTime", - expected: "LtTime deve ser anterior à data / hora atual", - }, - { - ns: "Test.NeString", - expected: "NeString não deve ser igual a ", - }, - { - ns: "Test.NeNumber", - expected: "NeNumber não deve ser igual a 0.00", - }, - { - ns: "Test.NeMultiple", - expected: "NeMultiple não deve ser igual a 0", - }, - { - ns: "Test.EqString", - expected: "EqString não é igual a 3", - }, - { - ns: "Test.EqNumber", - expected: "EqNumber não é igual a 2.33", - }, - { - ns: "Test.EqMultiple", - expected: "EqMultiple não é igual a 7", - }, - { - ns: "Test.MaxString", - expected: "MaxString deve ter no máximo 3 caracteres", - }, - { - ns: "Test.MaxNumber", - expected: "MaxNumber deve ser 1.113,00 ou menos", - }, - { - ns: "Test.MaxMultiple", - expected: "MaxMultiple deve conter no máximo 7 items", - }, - { - ns: "Test.MinString", - expected: "MinString deve ter pelo menos 1 caractere", - }, - { - ns: "Test.MinNumber", - expected: "MinNumber deve ser 1.113,00 ou superior", - }, - { - ns: "Test.MinMultiple", - expected: "MinMultiple deve conter pelo menos 7 items", - }, - { - ns: "Test.LenString", - expected: "LenString deve ter 1 caractere", - }, - { - ns: "Test.LenNumber", - expected: "LenNumber deve ser igual a 1.113,00", - }, - { - ns: "Test.LenMultiple", - expected: "LenMultiple deve conter 7 items", - }, - { - ns: "Test.RequiredString", - expected: "RequiredString é obrigatório", - }, - { - ns: "Test.RequiredNumber", - expected: "RequiredNumber é obrigatório", - }, - { - ns: "Test.RequiredMultiple", - expected: "RequiredMultiple é obrigatório", - }, - { - ns: "Test.StrPtrMinLen", - expected: "StrPtrMinLen deve ter pelo menos 10 caracteres", - }, - { - ns: "Test.StrPtrMaxLen", - expected: "StrPtrMaxLen deve ter no máximo 1 caractere", - }, - { - ns: "Test.StrPtrLen", - expected: "StrPtrLen deve ter 2 caracteres", - }, - { - ns: "Test.StrPtrLt", - expected: "StrPtrLt deve ter menos de 1 caractere", - }, - { - ns: "Test.StrPtrLte", - expected: "StrPtrLte deve ter no máximo 1 caractere", - }, - { - ns: "Test.StrPtrGt", - expected: "StrPtrGt deve conter mais de 10 caracteres", - }, - { - ns: "Test.StrPtrGte", - expected: "StrPtrGte deve ter pelo menos 10 caracteres", - }, - { - ns: "Test.OneOfString", - expected: "OneOfString deve ser um de [red green]", - }, - { - ns: "Test.OneOfInt", - expected: "OneOfInt deve ser um de [5 63]", - }, - { - ns: "Test.UniqueSlice", - expected: "UniqueSlice deve conter valores únicos", - }, - { - ns: "Test.UniqueArray", - expected: "UniqueArray deve conter valores únicos", - }, - { - ns: "Test.UniqueMap", - expected: "UniqueMap deve conter valores únicos", - }, - { - ns: "Test.JSONString", - expected: "JSONString deve ser uma string json válida", - }, - { - ns: "Test.LowercaseString", - expected: "LowercaseString deve estar em minuscúlas", - }, - { - ns: "Test.UppercaseString", - expected: "UppercaseString deve estar em maiúsculas", - }, - { - ns: "Test.Datetime", - expected: "Datetime não está no formato 2006-01-02", - }, - } - - for _, tt := range tests { - - var fe validator.FieldError - - for _, e := range errs { - if tt.ns == e.Namespace() { - fe = e - break - } - } - - NotEqual(t, fe, nil) - Equal(t, tt.expected, fe.Translate(trans)) - } - -} diff --git a/go-playground/validator/v10/translations/pt_BR/pt_BR.go b/go-playground/validator/v10/translations/pt_BR/pt_BR.go deleted file mode 100644 index 7f0e0aa..0000000 --- a/go-playground/validator/v10/translations/pt_BR/pt_BR.go +++ /dev/null @@ -1,1365 +0,0 @@ -package pt_BR - -import ( - "fmt" - "log" - "reflect" - "strconv" - "strings" - "time" - - "git.ningdatech.com/ningda/gin_valid/go-playground/locales" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -// RegisterDefaultTranslations registers a set of default translations -// for all built in tag's in validator; you may add your own as desired. -func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (err error) { - - translations := []struct { - tag string - translation string - override bool - customRegisFunc validator.RegisterTranslationsFunc - customTransFunc validator.TranslationFunc - }{ - { - tag: "required", - translation: "{0} é um campo requerido", - override: false, - }, - { - tag: "len", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("len-string", "{0} deve ter {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("len-string-character", "{0} caractere", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("len-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("len-number", "{0} deve ser igual a {1}", false); err != nil { - return - } - - if err = ut.Add("len-items", "{0} deve conter {1}", false); err != nil { - return - } - if err = ut.AddCardinal("len-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("len-items-item", "{0} itens", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("len-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("len-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-items", fe.Field(), c) - - default: - t, err = ut.T("len-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("alerta: erro na tradução FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "min", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("min-string", "{0} deve ter pelo menos {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("min-string-character", "{0} caractere", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("min-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("min-number", "{0} deve ser {1} ou superior", false); err != nil { - return - } - - if err = ut.Add("min-items", "{0} deve conter pelo menos {1}", false); err != nil { - return - } - if err = ut.AddCardinal("min-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("min-items-item", "{0} itens", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("min-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("min-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-items", fe.Field(), c) - - default: - t, err = ut.T("min-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("alerta: erro na tradução FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "max", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("max-string", "{0} deve ter no máximo {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("max-string-character", "{0} caractere", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("max-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("max-number", "{0} deve ser {1} ou menor", false); err != nil { - return - } - - if err = ut.Add("max-items", "{0} deve conter no máximo {1}", false); err != nil { - return - } - if err = ut.AddCardinal("max-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("max-items-item", "{0} itens", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("max-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("max-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-items", fe.Field(), c) - - default: - t, err = ut.T("max-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("alerta: erro na tradução FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eq", - translation: "{0} não é igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ne", - translation: "{0} não deve ser igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lt-string", "{0} deve ter menos de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lt-string-character", "{0} caractere", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lt-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-number", "{0} deve ser menor que {1}", false); err != nil { - return - } - - if err = ut.Add("lt-items", "{0} deve conter menos de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lt-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lt-items-item", "{0} itens", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-datetime", "{0} deve ser inferior à Data e Hora atual", false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("a tag '%s' não pode ser usada em uma struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("alerta: erro na tradução FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lte-string", "{0} deve ter no máximo {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lte-string-character", "{0} caractere", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lte-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-number", "{0} deve ser {1} ou menor", false); err != nil { - return - } - - if err = ut.Add("lte-items", "{0} deve conter no máximo {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lte-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lte-items-item", "{0} itens", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-datetime", "{0} deve ser menor ou igual à Data e Hora atual", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("a tag '%s' não pode ser usado em uma struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("alerta: erro na tradução FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gt-string", "{0} deve ter mais de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gt-string-character", "{0} caractere", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gt-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-number", "{0} deve ser maior do que {1}", false); err != nil { - return - } - - if err = ut.Add("gt-items", "{0} deve conter mais de {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gt-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gt-items-item", "{0} itens", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-datetime", "{0} deve ser maior que a Data e Hora atual", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("a tag '%s' não pode ser usado em uma struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("alerta: erro na tradução FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gte-string", "{0} deve ter pelo menos {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gte-string-character", "{0} caractere", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gte-string-character", "{0} caracteres", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-number", "{0} deve ser {1} ou superior", false); err != nil { - return - } - - if err = ut.Add("gte-items", "{0} deve conter pelo menos {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gte-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gte-items-item", "{0} itens", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-datetime", "{0} deve ser maior ou igual à Data e Hora atual", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("a tag '%s' não pode ser usado em uma struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("alerta: erro na tradução FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqfield", - translation: "{0} deve ser igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqcsfield", - translation: "{0} deve ser igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "necsfield", - translation: "{0} não deve ser igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtcsfield", - translation: "{0} deve ser maior do que {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtecsfield", - translation: "{0} deve ser maior ou igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltcsfield", - translation: "{0} deve ser menor que {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltecsfield", - translation: "{0} deve ser menor ou igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "nefield", - translation: "{0} não deve ser igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtfield", - translation: "{0} deve ser maior do que {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtefield", - translation: "{0} deve ser maior ou igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltfield", - translation: "{0} deve ser menor que {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltefield", - translation: "{0} deve ser menor ou igual a {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "alpha", - translation: "{0} deve conter caracteres alfabéticos", - override: false, - }, - { - tag: "alphanum", - translation: "{0} deve conter caracteres alfanuméricos", - override: false, - }, - { - tag: "numeric", - translation: "{0} deve ser um valor numérico válido", - override: false, - }, - { - tag: "number", - translation: "{0} deve ser um número válido", - override: false, - }, - { - tag: "hexadecimal", - translation: "{0} deve ser um hexadecimal válido", - override: false, - }, - { - tag: "hexcolor", - translation: "{0} deve ser uma cor HEX válida", - override: false, - }, - { - tag: "rgb", - translation: "{0} deve ser uma cor RGB válida", - override: false, - }, - { - tag: "rgba", - translation: "{0} deve ser uma cor RGBA válida", - override: false, - }, - { - tag: "hsl", - translation: "{0} deve ser uma cor HSL válida", - override: false, - }, - { - tag: "hsla", - translation: "{0} deve ser uma cor HSLA válida", - override: false, - }, - { - tag: "email", - translation: "{0} deve ser um endereço de e-mail válido", - override: false, - }, - { - tag: "url", - translation: "{0} deve ser uma URL válida", - override: false, - }, - { - tag: "uri", - translation: "{0} deve ser uma URI válida", - override: false, - }, - { - tag: "base64", - translation: "{0} deve ser uma string Base64 válida", - override: false, - }, - { - tag: "contains", - translation: "{0} deve conter o texto '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "containsany", - translation: "{0} deve conter pelo menos um dos caracteres '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludes", - translation: "{0} não deve conter o texto '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesall", - translation: "{0} não deve conter nenhum dos caracteres '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesrune", - translation: "{0} não deve conter '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "isbn", - translation: "{0} deve ser um número ISBN válido", - override: false, - }, - { - tag: "isbn10", - translation: "{0} deve ser um número ISBN-10 válido", - override: false, - }, - { - tag: "isbn13", - translation: "{0} deve ser um número ISBN-13 válido", - override: false, - }, - { - tag: "uuid", - translation: "{0} deve ser um UUID válido", - override: false, - }, - { - tag: "uuid3", - translation: "{0} deve ser um UUID versão 3 válido", - override: false, - }, - { - tag: "uuid4", - translation: "{0} deve ser um UUID versão 4 válido", - override: false, - }, - { - tag: "uuid5", - translation: "{0} deve ser um UUID versão 5 válido", - override: false, - }, - { - tag: "ascii", - translation: "{0} deve conter apenas caracteres ascii", - override: false, - }, - { - tag: "printascii", - translation: "{0} deve conter apenas caracteres ascii imprimíveis", - override: false, - }, - { - tag: "multibyte", - translation: "{0} deve conter caracteres multibyte", - override: false, - }, - { - tag: "datauri", - translation: "{0} deve conter um URI data válido", - override: false, - }, - { - tag: "latitude", - translation: "{0} deve conter uma coordenada de latitude válida", - override: false, - }, - { - tag: "longitude", - translation: "{0} deve conter uma coordenada de longitude válida", - override: false, - }, - { - tag: "ssn", - translation: "{0} deve ser um número SSN válido", - override: false, - }, - { - tag: "ipv4", - translation: "{0} deve ser um endereço IPv4 válido", - override: false, - }, - { - tag: "ipv6", - translation: "{0} deve ser um endereço IPv6 válido", - override: false, - }, - { - tag: "ip", - translation: "{0} deve ser um endereço de IP válido", - override: false, - }, - { - tag: "cidr", - translation: "{0} deve conter uma notação CIDR válida", - override: false, - }, - { - tag: "cidrv4", - translation: "{0} deve conter uma notação CIDR válida para um endereço IPv4", - override: false, - }, - { - tag: "cidrv6", - translation: "{0} deve conter uma notação CIDR válida para um endereço IPv6", - override: false, - }, - { - tag: "tcp_addr", - translation: "{0} deve ser um endereço TCP válido", - override: false, - }, - { - tag: "tcp4_addr", - translation: "{0} deve ser um endereço IPv4 TCP válido", - override: false, - }, - { - tag: "tcp6_addr", - translation: "{0} deve ser um endereço IPv6 TCP válido", - override: false, - }, - { - tag: "udp_addr", - translation: "{0} deve ser um endereço UDP válido", - override: false, - }, - { - tag: "udp4_addr", - translation: "{0} deve ser um endereço IPv4 UDP válido", - override: false, - }, - { - tag: "udp6_addr", - translation: "{0} deve ser um endereço IPv6 UDP válido", - override: false, - }, - { - tag: "ip_addr", - translation: "{0} deve ser um endereço IP resolvível", - override: false, - }, - { - tag: "ip4_addr", - translation: "{0} deve ser um endereço IPv4 resolvível", - override: false, - }, - { - tag: "ip6_addr", - translation: "{0} deve ser um endereço IPv6 resolvível", - override: false, - }, - { - tag: "unix_addr", - translation: "{0} deve ser um endereço UNIX resolvível", - override: false, - }, - { - tag: "mac", - translation: "{0} deve conter um endereço MAC válido", - override: false, - }, - { - tag: "iscolor", - translation: "{0} deve ser uma cor válida", - override: false, - }, - { - tag: "oneof", - translation: "{0} deve ser um de [{1}]", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - s, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - return s - }, - }, - } - - for _, t := range translations { - - if t.customTransFunc != nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, t.customTransFunc) - - } else if t.customTransFunc != nil && t.customRegisFunc == nil { - - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), t.customTransFunc) - - } else if t.customTransFunc == nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, translateFunc) - - } else { - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), translateFunc) - } - - if err != nil { - return - } - } - - return -} - -func registrationFunc(tag string, translation string, override bool) validator.RegisterTranslationsFunc { - - return func(ut ut.Translator) (err error) { - - if err = ut.Add(tag, translation, override); err != nil { - return - } - - return - - } - -} - -func translateFunc(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field()) - if err != nil { - log.Printf("alerta: erro na tradução FieldError: %#v", fe) - return fe.(error).Error() - } - - return t -} diff --git a/go-playground/validator/v10/translations/pt_BR/pt_BR_test.go b/go-playground/validator/v10/translations/pt_BR/pt_BR_test.go deleted file mode 100644 index fc7bbd2..0000000 --- a/go-playground/validator/v10/translations/pt_BR/pt_BR_test.go +++ /dev/null @@ -1,634 +0,0 @@ -package pt_BR - -import ( - "testing" - "time" - - . "git.ningdatech.com/ningda/gin_valid/go-playground/assert/v2" - brazilian_portuguese "git.ningdatech.com/ningda/gin_valid/go-playground/locales/pt_BR" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -func TestTranslations(t *testing.T) { - - ptbr := brazilian_portuguese.New() - uni := ut.New(ptbr, ptbr) - trans, _ := uni.GetTranslator("pt_BR") - - validate := validator.New() - - err := RegisterDefaultTranslations(validate, trans) - Equal(t, err, nil) - - type Inner struct { - EqCSFieldString string - NeCSFieldString string - GtCSFieldString string - GteCSFieldString string - LtCSFieldString string - LteCSFieldString string - } - - type Test struct { - Inner Inner - RequiredString string `validate:"required"` - RequiredNumber int `validate:"required"` - RequiredMultiple []string `validate:"required"` - LenString string `validate:"len=1"` - LenNumber float64 `validate:"len=1113.00"` - LenMultiple []string `validate:"len=7"` - MinString string `validate:"min=1"` - MinNumber float64 `validate:"min=1113.00"` - MinMultiple []string `validate:"min=7"` - MaxString string `validate:"max=3"` - MaxNumber float64 `validate:"max=1113.00"` - MaxMultiple []string `validate:"max=7"` - EqString string `validate:"eq=3"` - EqNumber float64 `validate:"eq=2.33"` - EqMultiple []string `validate:"eq=7"` - NeString string `validate:"ne="` - NeNumber float64 `validate:"ne=0.00"` - NeMultiple []string `validate:"ne=0"` - LtString string `validate:"lt=3"` - LtNumber float64 `validate:"lt=5.56"` - LtMultiple []string `validate:"lt=2"` - LtTime time.Time `validate:"lt"` - LteString string `validate:"lte=3"` - LteNumber float64 `validate:"lte=5.56"` - LteMultiple []string `validate:"lte=2"` - LteTime time.Time `validate:"lte"` - GtString string `validate:"gt=3"` - GtNumber float64 `validate:"gt=5.56"` - GtMultiple []string `validate:"gt=2"` - GtTime time.Time `validate:"gt"` - GteString string `validate:"gte=3"` - GteNumber float64 `validate:"gte=5.56"` - GteMultiple []string `validate:"gte=2"` - GteTime time.Time `validate:"gte"` - EqFieldString string `validate:"eqfield=MaxString"` - EqCSFieldString string `validate:"eqcsfield=Inner.EqCSFieldString"` - NeCSFieldString string `validate:"necsfield=Inner.NeCSFieldString"` - GtCSFieldString string `validate:"gtcsfield=Inner.GtCSFieldString"` - GteCSFieldString string `validate:"gtecsfield=Inner.GteCSFieldString"` - LtCSFieldString string `validate:"ltcsfield=Inner.LtCSFieldString"` - LteCSFieldString string `validate:"ltecsfield=Inner.LteCSFieldString"` - NeFieldString string `validate:"nefield=EqFieldString"` - GtFieldString string `validate:"gtfield=MaxString"` - GteFieldString string `validate:"gtefield=MaxString"` - LtFieldString string `validate:"ltfield=MaxString"` - LteFieldString string `validate:"ltefield=MaxString"` - AlphaString string `validate:"alpha"` - AlphanumString string `validate:"alphanum"` - NumericString string `validate:"numeric"` - NumberString string `validate:"number"` - HexadecimalString string `validate:"hexadecimal"` - HexColorString string `validate:"hexcolor"` - RGBColorString string `validate:"rgb"` - RGBAColorString string `validate:"rgba"` - HSLColorString string `validate:"hsl"` - HSLAColorString string `validate:"hsla"` - Email string `validate:"email"` - URL string `validate:"url"` - URI string `validate:"uri"` - Base64 string `validate:"base64"` - Contains string `validate:"contains=purpose"` - ContainsAny string `validate:"containsany=!@#$"` - Excludes string `validate:"excludes=text"` - ExcludesAll string `validate:"excludesall=!@#$"` - ExcludesRune string `validate:"excludesrune=☻"` - ISBN string `validate:"isbn"` - ISBN10 string `validate:"isbn10"` - ISBN13 string `validate:"isbn13"` - UUID string `validate:"uuid"` - UUID3 string `validate:"uuid3"` - UUID4 string `validate:"uuid4"` - UUID5 string `validate:"uuid5"` - ASCII string `validate:"ascii"` - PrintableASCII string `validate:"printascii"` - MultiByte string `validate:"multibyte"` - DataURI string `validate:"datauri"` - Latitude string `validate:"latitude"` - Longitude string `validate:"longitude"` - SSN string `validate:"ssn"` - IP string `validate:"ip"` - IPv4 string `validate:"ipv4"` - IPv6 string `validate:"ipv6"` - CIDR string `validate:"cidr"` - CIDRv4 string `validate:"cidrv4"` - CIDRv6 string `validate:"cidrv6"` - TCPAddr string `validate:"tcp_addr"` - TCPAddrv4 string `validate:"tcp4_addr"` - TCPAddrv6 string `validate:"tcp6_addr"` - UDPAddr string `validate:"udp_addr"` - UDPAddrv4 string `validate:"udp4_addr"` - UDPAddrv6 string `validate:"udp6_addr"` - IPAddr string `validate:"ip_addr"` - IPAddrv4 string `validate:"ip4_addr"` - IPAddrv6 string `validate:"ip6_addr"` - UinxAddr string `validate:"unix_addr"` // can't fail from within Go's net package currently, but maybe in the future - MAC string `validate:"mac"` - IsColor string `validate:"iscolor"` - StrPtrMinLen *string `validate:"min=10"` - StrPtrMaxLen *string `validate:"max=1"` - StrPtrLen *string `validate:"len=2"` - StrPtrLt *string `validate:"lt=1"` - StrPtrLte *string `validate:"lte=1"` - StrPtrGt *string `validate:"gt=10"` - StrPtrGte *string `validate:"gte=10"` - OneOfString string `validate:"oneof=red green"` - OneOfInt int `validate:"oneof=5 63"` - } - - var test Test - - test.Inner.EqCSFieldString = "1234" - test.Inner.GtCSFieldString = "1234" - test.Inner.GteCSFieldString = "1234" - - test.MaxString = "1234" - test.MaxNumber = 2000 - test.MaxMultiple = make([]string, 9) - - test.LtString = "1234" - test.LtNumber = 6 - test.LtMultiple = make([]string, 3) - test.LtTime = time.Now().Add(time.Hour * 24) - - test.LteString = "1234" - test.LteNumber = 6 - test.LteMultiple = make([]string, 3) - test.LteTime = time.Now().Add(time.Hour * 24) - - test.LtFieldString = "12345" - test.LteFieldString = "12345" - - test.LtCSFieldString = "1234" - test.LteCSFieldString = "1234" - - test.AlphaString = "abc3" - test.AlphanumString = "abc3!" - test.NumericString = "12E.00" - test.NumberString = "12E" - - test.Excludes = "este é um texto de teste" - test.ExcludesAll = "Isso é Ótimo!" - test.ExcludesRune = "Amo isso ☻" - - test.ASCII = "カタカナ" - test.PrintableASCII = "カタカナ" - - test.MultiByte = "1234feerf" - - s := "toolong" - test.StrPtrMaxLen = &s - test.StrPtrLen = &s - - err = validate.Struct(test) - NotEqual(t, err, nil) - - errs, ok := err.(validator.ValidationErrors) - Equal(t, ok, true) - - tests := []struct { - ns string - expected string - }{ - { - ns: "Test.IsColor", - expected: "IsColor deve ser uma cor válida", - }, - { - ns: "Test.MAC", - expected: "MAC deve conter um endereço MAC válido", - }, - { - ns: "Test.IPAddr", - expected: "IPAddr deve ser um endereço IP resolvível", - }, - { - ns: "Test.IPAddrv4", - expected: "IPAddrv4 deve ser um endereço IPv4 resolvível", - }, - { - ns: "Test.IPAddrv6", - expected: "IPAddrv6 deve ser um endereço IPv6 resolvível", - }, - { - ns: "Test.UDPAddr", - expected: "UDPAddr deve ser um endereço UDP válido", - }, - { - ns: "Test.UDPAddrv4", - expected: "UDPAddrv4 deve ser um endereço IPv4 UDP válido", - }, - { - ns: "Test.UDPAddrv6", - expected: "UDPAddrv6 deve ser um endereço IPv6 UDP válido", - }, - { - ns: "Test.TCPAddr", - expected: "TCPAddr deve ser um endereço TCP válido", - }, - { - ns: "Test.TCPAddrv4", - expected: "TCPAddrv4 deve ser um endereço IPv4 TCP válido", - }, - { - ns: "Test.TCPAddrv6", - expected: "TCPAddrv6 deve ser um endereço IPv6 TCP válido", - }, - { - ns: "Test.CIDR", - expected: "CIDR deve conter uma notação CIDR válida", - }, - { - ns: "Test.CIDRv4", - expected: "CIDRv4 deve conter uma notação CIDR válida para um endereço IPv4", - }, - { - ns: "Test.CIDRv6", - expected: "CIDRv6 deve conter uma notação CIDR válida para um endereço IPv6", - }, - { - ns: "Test.SSN", - expected: "SSN deve ser um número SSN válido", - }, - { - ns: "Test.IP", - expected: "IP deve ser um endereço de IP válido", - }, - { - ns: "Test.IPv4", - expected: "IPv4 deve ser um endereço IPv4 válido", - }, - { - ns: "Test.IPv6", - expected: "IPv6 deve ser um endereço IPv6 válido", - }, - { - ns: "Test.DataURI", - expected: "DataURI deve conter um URI data válido", - }, - { - ns: "Test.Latitude", - expected: "Latitude deve conter uma coordenada de latitude válida", - }, - { - ns: "Test.Longitude", - expected: "Longitude deve conter uma coordenada de longitude válida", - }, - { - ns: "Test.MultiByte", - expected: "MultiByte deve conter caracteres multibyte", - }, - { - ns: "Test.ASCII", - expected: "ASCII deve conter apenas caracteres ascii", - }, - { - ns: "Test.PrintableASCII", - expected: "PrintableASCII deve conter apenas caracteres ascii imprimíveis", - }, - { - ns: "Test.UUID", - expected: "UUID deve ser um UUID válido", - }, - { - ns: "Test.UUID3", - expected: "UUID3 deve ser um UUID versão 3 válido", - }, - { - ns: "Test.UUID4", - expected: "UUID4 deve ser um UUID versão 4 válido", - }, - { - ns: "Test.UUID5", - expected: "UUID5 deve ser um UUID versão 5 válido", - }, - { - ns: "Test.ISBN", - expected: "ISBN deve ser um número ISBN válido", - }, - { - ns: "Test.ISBN10", - expected: "ISBN10 deve ser um número ISBN-10 válido", - }, - { - ns: "Test.ISBN13", - expected: "ISBN13 deve ser um número ISBN-13 válido", - }, - { - ns: "Test.Excludes", - expected: "Excludes não deve conter o texto 'text'", - }, - { - ns: "Test.ExcludesAll", - expected: "ExcludesAll não deve conter nenhum dos caracteres '!@#$'", - }, - { - ns: "Test.ExcludesRune", - expected: "ExcludesRune não deve conter '☻'", - }, - { - ns: "Test.ContainsAny", - expected: "ContainsAny deve conter pelo menos um dos caracteres '!@#$'", - }, - { - ns: "Test.Contains", - expected: "Contains deve conter o texto 'purpose'", - }, - { - ns: "Test.Base64", - expected: "Base64 deve ser uma string Base64 válida", - }, - { - ns: "Test.Email", - expected: "Email deve ser um endereço de e-mail válido", - }, - { - ns: "Test.URL", - expected: "URL deve ser uma URL válida", - }, - { - ns: "Test.URI", - expected: "URI deve ser uma URI válida", - }, - { - ns: "Test.RGBColorString", - expected: "RGBColorString deve ser uma cor RGB válida", - }, - { - ns: "Test.RGBAColorString", - expected: "RGBAColorString deve ser uma cor RGBA válida", - }, - { - ns: "Test.HSLColorString", - expected: "HSLColorString deve ser uma cor HSL válida", - }, - { - ns: "Test.HSLAColorString", - expected: "HSLAColorString deve ser uma cor HSLA válida", - }, - { - ns: "Test.HexadecimalString", - expected: "HexadecimalString deve ser um hexadecimal válido", - }, - { - ns: "Test.HexColorString", - expected: "HexColorString deve ser uma cor HEX válida", - }, - { - ns: "Test.NumberString", - expected: "NumberString deve ser um número válido", - }, - { - ns: "Test.NumericString", - expected: "NumericString deve ser um valor numérico válido", - }, - { - ns: "Test.AlphanumString", - expected: "AlphanumString deve conter caracteres alfanuméricos", - }, - { - ns: "Test.AlphaString", - expected: "AlphaString deve conter caracteres alfabéticos", - }, - { - ns: "Test.LtFieldString", - expected: "LtFieldString deve ser menor que MaxString", - }, - { - ns: "Test.LteFieldString", - expected: "LteFieldString deve ser menor ou igual a MaxString", - }, - { - ns: "Test.GtFieldString", - expected: "GtFieldString deve ser maior do que MaxString", - }, - { - ns: "Test.GteFieldString", - expected: "GteFieldString deve ser maior ou igual a MaxString", - }, - { - ns: "Test.NeFieldString", - expected: "NeFieldString não deve ser igual a EqFieldString", - }, - { - ns: "Test.LtCSFieldString", - expected: "LtCSFieldString deve ser menor que Inner.LtCSFieldString", - }, - { - ns: "Test.LteCSFieldString", - expected: "LteCSFieldString deve ser menor ou igual a Inner.LteCSFieldString", - }, - { - ns: "Test.GtCSFieldString", - expected: "GtCSFieldString deve ser maior do que Inner.GtCSFieldString", - }, - { - ns: "Test.GteCSFieldString", - expected: "GteCSFieldString deve ser maior ou igual a Inner.GteCSFieldString", - }, - { - ns: "Test.NeCSFieldString", - expected: "NeCSFieldString não deve ser igual a Inner.NeCSFieldString", - }, - { - ns: "Test.EqCSFieldString", - expected: "EqCSFieldString deve ser igual a Inner.EqCSFieldString", - }, - { - ns: "Test.EqFieldString", - expected: "EqFieldString deve ser igual a MaxString", - }, - { - ns: "Test.GteString", - expected: "GteString deve ter pelo menos 3 caracteres", - }, - { - ns: "Test.GteNumber", - expected: "GteNumber deve ser 5,56 ou superior", - }, - { - ns: "Test.GteMultiple", - expected: "GteMultiple deve conter pelo menos 2 itens", - }, - { - ns: "Test.GteTime", - expected: "GteTime deve ser maior ou igual à Data e Hora atual", - }, - { - ns: "Test.GtString", - expected: "GtString deve ter mais de 3 caracteres", - }, - { - ns: "Test.GtNumber", - expected: "GtNumber deve ser maior do que 5,56", - }, - { - ns: "Test.GtMultiple", - expected: "GtMultiple deve conter mais de 2 itens", - }, - { - ns: "Test.GtTime", - expected: "GtTime deve ser maior que a Data e Hora atual", - }, - { - ns: "Test.LteString", - expected: "LteString deve ter no máximo 3 caracteres", - }, - { - ns: "Test.LteNumber", - expected: "LteNumber deve ser 5,56 ou menor", - }, - { - ns: "Test.LteMultiple", - expected: "LteMultiple deve conter no máximo 2 itens", - }, - { - ns: "Test.LteTime", - expected: "LteTime deve ser menor ou igual à Data e Hora atual", - }, - { - ns: "Test.LtString", - expected: "LtString deve ter menos de 3 caracteres", - }, - { - ns: "Test.LtNumber", - expected: "LtNumber deve ser menor que 5,56", - }, - { - ns: "Test.LtMultiple", - expected: "LtMultiple deve conter menos de 2 itens", - }, - { - ns: "Test.LtTime", - expected: "LtTime deve ser inferior à Data e Hora atual", - }, - { - ns: "Test.NeString", - expected: "NeString não deve ser igual a ", - }, - { - ns: "Test.NeNumber", - expected: "NeNumber não deve ser igual a 0.00", - }, - { - ns: "Test.NeMultiple", - expected: "NeMultiple não deve ser igual a 0", - }, - { - ns: "Test.EqString", - expected: "EqString não é igual a 3", - }, - { - ns: "Test.EqNumber", - expected: "EqNumber não é igual a 2.33", - }, - { - ns: "Test.EqMultiple", - expected: "EqMultiple não é igual a 7", - }, - { - ns: "Test.MaxString", - expected: "MaxString deve ter no máximo 3 caracteres", - }, - { - ns: "Test.MaxNumber", - expected: "MaxNumber deve ser 1.113,00 ou menor", - }, - { - ns: "Test.MaxMultiple", - expected: "MaxMultiple deve conter no máximo 7 itens", - }, - { - ns: "Test.MinString", - expected: "MinString deve ter pelo menos 1 caractere", - }, - { - ns: "Test.MinNumber", - expected: "MinNumber deve ser 1.113,00 ou superior", - }, - { - ns: "Test.MinMultiple", - expected: "MinMultiple deve conter pelo menos 7 itens", - }, - { - ns: "Test.LenString", - expected: "LenString deve ter 1 caractere", - }, - { - ns: "Test.LenNumber", - expected: "LenNumber deve ser igual a 1.113,00", - }, - { - ns: "Test.LenMultiple", - expected: "LenMultiple deve conter 7 itens", - }, - { - ns: "Test.RequiredString", - expected: "RequiredString é um campo requerido", - }, - { - ns: "Test.RequiredNumber", - expected: "RequiredNumber é um campo requerido", - }, - { - ns: "Test.RequiredMultiple", - expected: "RequiredMultiple é um campo requerido", - }, - { - ns: "Test.StrPtrMinLen", - expected: "StrPtrMinLen deve ter pelo menos 10 caracteres", - }, - { - ns: "Test.StrPtrMaxLen", - expected: "StrPtrMaxLen deve ter no máximo 1 caractere", - }, - { - ns: "Test.StrPtrLen", - expected: "StrPtrLen deve ter 2 caracteres", - }, - { - ns: "Test.StrPtrLt", - expected: "StrPtrLt deve ter menos de 1 caractere", - }, - { - ns: "Test.StrPtrLte", - expected: "StrPtrLte deve ter no máximo 1 caractere", - }, - { - ns: "Test.StrPtrGt", - expected: "StrPtrGt deve ter mais de 10 caracteres", - }, - { - ns: "Test.StrPtrGte", - expected: "StrPtrGte deve ter pelo menos 10 caracteres", - }, - { - ns: "Test.OneOfString", - expected: "OneOfString deve ser um de [red green]", - }, - { - ns: "Test.OneOfInt", - expected: "OneOfInt deve ser um de [5 63]", - }, - } - - for _, tt := range tests { - - var fe validator.FieldError - - for _, e := range errs { - if tt.ns == e.Namespace() { - fe = e - break - } - } - - NotEqual(t, fe, nil) - Equal(t, tt.expected, fe.Translate(trans)) - } - -} diff --git a/go-playground/validator/v10/translations/ru/ru.go b/go-playground/validator/v10/translations/ru/ru.go deleted file mode 100644 index 54ea05d..0000000 --- a/go-playground/validator/v10/translations/ru/ru.go +++ /dev/null @@ -1,1375 +0,0 @@ -package ru - -import ( - "fmt" - "log" - "reflect" - "strconv" - "strings" - "time" - - "git.ningdatech.com/ningda/gin_valid/go-playground/locales" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -// RegisterDefaultTranslations registers a set of default translations -// for all built in tag's in validator; you may add your own as desired. -func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (err error) { - - translations := []struct { - tag string - translation string - override bool - customRegisFunc validator.RegisterTranslationsFunc - customTransFunc validator.TranslationFunc - }{ - { - tag: "required", - translation: "{0} обязательное поле", - override: false, - }, - { - tag: "len", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("len-string", "{0} должен быть длиной в {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("len-string-character", "{0} символ", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("len-string-character", "{0} символы", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("len-number", "{0} должен быть равен {1}", false); err != nil { - return - } - - if err = ut.Add("len-items", "{0} должен содержать {1}", false); err != nil { - return - } - if err = ut.AddCardinal("len-items-item", "{0} элемент", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("len-items-item", "{0} элементы", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("len-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("len-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-items", fe.Field(), c) - - default: - t, err = ut.T("len-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "min", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("min-string", "{0} должен содержать минимум {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("min-string-character", "{0} символ", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("min-string-character", "{0} символы", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("min-number", "{0} должен быть больше или равно {1}", false); err != nil { - return - } - - if err = ut.Add("min-items", "{0} должен содержать минимум {1}", false); err != nil { - return - } - if err = ut.AddCardinal("min-items-item", "{0} элемент", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("min-items-item", "{0} элементы", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("min-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("min-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-items", fe.Field(), c) - - default: - t, err = ut.T("min-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "max", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("max-string", "{0} должен содержать максимум {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("max-string-character", "{0} символ", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("max-string-character", "{0} символы", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("max-number", "{0} должен быть меньше или равно {1}", false); err != nil { - return - } - - if err = ut.Add("max-items", "{0} должен содержать максимум {1}", false); err != nil { - return - } - if err = ut.AddCardinal("max-items-item", "{0} элемент", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("max-items-item", "{0} элементы", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("max-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("max-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-items", fe.Field(), c) - - default: - t, err = ut.T("max-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eq", - translation: "{0} не равен {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ne", - translation: "{0} должен быть не равен {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lt-string", "{0} должен иметь менее {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lt-string-character", "{0} символ", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lt-string-character", "{0} символы", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-number", "{0} должен быть менее {1}", false); err != nil { - return - } - - if err = ut.Add("lt-items", "{0} должен содержать менее {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lt-items-item", "{0} элемент", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lt-items-item", "{0} элементы", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-datetime", "{0} must be less than the current Date & Time", false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lte-string", "{0} должен содержать максимум {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lte-string-character", "{0} символ", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lte-string-character", "{0} символы", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-number", "{0} должен быть менее или равен {1}", false); err != nil { - return - } - - if err = ut.Add("lte-items", "{0} должен содержать максимум {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("lte-items-item", "{0} элемент", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lte-items-item", "{0} элементы", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-datetime", "{0} must be less than or equal to the current Date & Time", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gt-string", "{0} должен быть длиннее {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gt-string-character", "{0} символ", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gt-string-character", "{0} символы", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-number", "{0} должен быть больше {1}", false); err != nil { - return - } - - if err = ut.Add("gt-items", "{0} должен содержать более {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gt-items-item", "{0} элемент", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gt-items-item", "{0} элементы", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-datetime", "{0} должна быть позже текущего момента", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gte-string", "{0} должен содержать минимум {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gte-string-character", "{0} символ", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gte-string-character", "{0} символы", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-number", "{0} должен быть больше или равно {1}", false); err != nil { - return - } - - if err = ut.Add("gte-items", "{0} должен содержать минимум {1}", false); err != nil { - return - } - - if err = ut.AddCardinal("gte-items-item", "{0} элемент", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gte-items-item", "{0} элементы", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-datetime", "{0} должна быть позже или равна текущему моменту", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqfield", - translation: "{0} должен быть равен {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqcsfield", - translation: "{0} должен быть равен {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "necsfield", - translation: "{0} не должен быть равен {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtcsfield", - translation: "{0} должен быть больше {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtecsfield", - translation: "{0} должен быть больше или равен {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltcsfield", - translation: "{0} должен быть менее {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltecsfield", - translation: "{0} должен быть менее или равен {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "nefield", - translation: "{0} не должен быть равен {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtfield", - translation: "{0} должен быть больше {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtefield", - translation: "{0} должен быть больше или равен {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltfield", - translation: "{0} должен быть менее {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltefield", - translation: "{0} должен быть менее или равен {1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "alpha", - translation: "{0} должен содержать только буквы", - override: false, - }, - { - tag: "alphanum", - translation: "{0} должен содержать только буквы и цифры", - override: false, - }, - { - tag: "numeric", - translation: "{0} должен быть цифровым значением", - override: false, - }, - { - tag: "number", - translation: "{0} должен быть цифрой", - override: false, - }, - { - tag: "hexadecimal", - translation: "{0} должен быть шестнадцатеричной строкой", - override: false, - }, - { - tag: "hexcolor", - translation: "{0} должен быть HEX цветом", - override: false, - }, - { - tag: "rgb", - translation: "{0} должен быть RGB цветом", - override: false, - }, - { - tag: "rgba", - translation: "{0} должен быть RGBA цветом", - override: false, - }, - { - tag: "hsl", - translation: "{0} должен быть HSL цветом", - override: false, - }, - { - tag: "hsla", - translation: "{0} должен быть HSLA цветом", - override: false, - }, - { - tag: "e164", - translation: "{0} должен быть E.164 formatted phone number", - override: false, - }, - { - tag: "email", - translation: "{0} должен быть email адресом", - override: false, - }, - { - tag: "url", - translation: "{0} должен быть URL", - override: false, - }, - { - tag: "uri", - translation: "{0} должен быть URI", - override: false, - }, - { - tag: "base64", - translation: "{0} должен быть Base64 строкой", - override: false, - }, - { - tag: "contains", - translation: "{0} должен содержать текст '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "containsany", - translation: "{0} должен содержать минимум один из символов '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludes", - translation: "{0} не должен содержать текст '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesall", - translation: "{0} не должен содержать символы '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesrune", - translation: "{0} не должен содержать '{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "isbn", - translation: "{0} должен быть ISBN номером", - override: false, - }, - { - tag: "isbn10", - translation: "{0} должен быть ISBN-10 номером", - override: false, - }, - { - tag: "isbn13", - translation: "{0} должен быть ISBN-13 номером", - override: false, - }, - { - tag: "uuid", - translation: "{0} должен быть UUID", - override: false, - }, - { - tag: "uuid3", - translation: "{0} должен быть UUID 3 версии", - override: false, - }, - { - tag: "uuid4", - translation: "{0} должен быть UUID 4 версии", - override: false, - }, - { - tag: "uuid5", - translation: "{0} должен быть UUID 5 версии", - override: false, - }, - { - tag: "ascii", - translation: "{0} должен содержать только ascii символы", - override: false, - }, - { - tag: "printascii", - translation: "{0} должен содержать только доступные для печати ascii символы", - override: false, - }, - { - tag: "multibyte", - translation: "{0} должен содержать мультибайтные символы", - override: false, - }, - { - tag: "datauri", - translation: "{0} должен содержать Data URI", - override: false, - }, - { - tag: "latitude", - translation: "{0} должен содержать координаты широты", - override: false, - }, - { - tag: "longitude", - translation: "{0} должен содержать координаты долготы", - override: false, - }, - { - tag: "ssn", - translation: "{0} должен быть SSN номером", - override: false, - }, - { - tag: "ipv4", - translation: "{0} должен быть IPv4 адресом", - override: false, - }, - { - tag: "ipv6", - translation: "{0} должен быть IPv6 адресом", - override: false, - }, - { - tag: "ip", - translation: "{0} должен быть IP адресом", - override: false, - }, - { - tag: "cidr", - translation: "{0} должен содержать CIDR обозначения", - override: false, - }, - { - tag: "cidrv4", - translation: "{0} должен содержать CIDR обозначения для IPv4 адреса", - override: false, - }, - { - tag: "cidrv6", - translation: "{0} должен содержать CIDR обозначения для IPv6 адреса", - override: false, - }, - { - tag: "tcp_addr", - translation: "{0} должен быть TCP адресом", - override: false, - }, - { - tag: "tcp4_addr", - translation: "{0} должен быть IPv4 TCP адресом", - override: false, - }, - { - tag: "tcp6_addr", - translation: "{0} должен быть IPv6 TCP адресом", - override: false, - }, - { - tag: "udp_addr", - translation: "{0} должен быть UDP адресом", - override: false, - }, - { - tag: "udp4_addr", - translation: "{0} должен быть IPv4 UDP адресом", - override: false, - }, - { - tag: "udp6_addr", - translation: "{0} должен быть IPv6 UDP адресом", - override: false, - }, - { - tag: "ip_addr", - translation: "{0} должен быть распознаваемым IP адресом", - override: false, - }, - { - tag: "ip4_addr", - translation: "{0} должен быть распознаваемым IPv4 адресом", - override: false, - }, - { - tag: "ip6_addr", - translation: "{0} должен быть распознаваемым IPv6 адресом", - override: false, - }, - { - tag: "unix_addr", - translation: "{0} должен быть распознаваемым UNIX адресом", - override: false, - }, - { - tag: "mac", - translation: "{0} должен содержать MAC адрес", - override: false, - }, - { - tag: "unique", - translation: "{0} должен содержать уникальные значения", - override: false, - }, - { - tag: "iscolor", - translation: "{0} должен быть цветом", - override: false, - }, - { - tag: "oneof", - translation: "{0} должен быть одним из [{1}]", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - s, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - return s - }, - }, - } - - for _, t := range translations { - - if t.customTransFunc != nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, t.customTransFunc) - - } else if t.customTransFunc != nil && t.customRegisFunc == nil { - - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), t.customTransFunc) - - } else if t.customTransFunc == nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, translateFunc) - - } else { - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), translateFunc) - } - - if err != nil { - return - } - } - - return -} - -func registrationFunc(tag string, translation string, override bool) validator.RegisterTranslationsFunc { - - return func(ut ut.Translator) (err error) { - - if err = ut.Add(tag, translation, override); err != nil { - return - } - - return - - } - -} - -func translateFunc(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t -} diff --git a/go-playground/validator/v10/translations/ru/ru_test.go b/go-playground/validator/v10/translations/ru/ru_test.go deleted file mode 100644 index e222aaf..0000000 --- a/go-playground/validator/v10/translations/ru/ru_test.go +++ /dev/null @@ -1,656 +0,0 @@ -package ru - -import ( - "log" - //"github.com/rustery/validator" - "testing" - "time" - - . "git.ningdatech.com/ningda/gin_valid/go-playground/assert/v2" - russian "git.ningdatech.com/ningda/gin_valid/go-playground/locales/en" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -func TestTranslations(t *testing.T) { - - ru := russian.New() - uni := ut.New(ru, ru) - trans, _ := uni.GetTranslator("ru") - - validate := validator.New() - - err := RegisterDefaultTranslations(validate, trans) - Equal(t, err, nil) - - type Inner struct { - EqCSFieldString string - NeCSFieldString string - GtCSFieldString string - GteCSFieldString string - LtCSFieldString string - LteCSFieldString string - } - - type Test struct { - Inner Inner - RequiredString string `validate:"required"` - RequiredNumber int `validate:"required"` - RequiredMultiple []string `validate:"required"` - LenString string `validate:"len=1"` - LenNumber float64 `validate:"len=1113.00"` - LenMultiple []string `validate:"len=7"` - MinString string `validate:"min=1"` - MinNumber float64 `validate:"min=1113.00"` - MinMultiple []string `validate:"min=7"` - MaxString string `validate:"max=3"` - MaxNumber float64 `validate:"max=1113.00"` - MaxMultiple []string `validate:"max=7"` - EqString string `validate:"eq=3"` - EqNumber float64 `validate:"eq=2.33"` - EqMultiple []string `validate:"eq=7"` - NeString string `validate:"ne="` - NeNumber float64 `validate:"ne=0.00"` - NeMultiple []string `validate:"ne=0"` - LtString string `validate:"lt=3"` - LtNumber float64 `validate:"lt=5.56"` - LtMultiple []string `validate:"lt=2"` - LtTime time.Time `validate:"lt"` - LteString string `validate:"lte=3"` - LteNumber float64 `validate:"lte=5.56"` - LteMultiple []string `validate:"lte=2"` - LteTime time.Time `validate:"lte"` - GtString string `validate:"gt=3"` - GtNumber float64 `validate:"gt=5.56"` - GtMultiple []string `validate:"gt=2"` - GtTime time.Time `validate:"gt"` - GteString string `validate:"gte=3"` - GteNumber float64 `validate:"gte=5.56"` - GteMultiple []string `validate:"gte=2"` - GteTime time.Time `validate:"gte"` - EqFieldString string `validate:"eqfield=MaxString"` - EqCSFieldString string `validate:"eqcsfield=Inner.EqCSFieldString"` - NeCSFieldString string `validate:"necsfield=Inner.NeCSFieldString"` - GtCSFieldString string `validate:"gtcsfield=Inner.GtCSFieldString"` - GteCSFieldString string `validate:"gtecsfield=Inner.GteCSFieldString"` - LtCSFieldString string `validate:"ltcsfield=Inner.LtCSFieldString"` - LteCSFieldString string `validate:"ltecsfield=Inner.LteCSFieldString"` - NeFieldString string `validate:"nefield=EqFieldString"` - GtFieldString string `validate:"gtfield=MaxString"` - GteFieldString string `validate:"gtefield=MaxString"` - LtFieldString string `validate:"ltfield=MaxString"` - LteFieldString string `validate:"ltefield=MaxString"` - AlphaString string `validate:"alpha"` - AlphanumString string `validate:"alphanum"` - NumericString string `validate:"numeric"` - NumberString string `validate:"number"` - HexadecimalString string `validate:"hexadecimal"` - HexColorString string `validate:"hexcolor"` - RGBColorString string `validate:"rgb"` - RGBAColorString string `validate:"rgba"` - HSLColorString string `validate:"hsl"` - HSLAColorString string `validate:"hsla"` - Email string `validate:"email"` - URL string `validate:"url"` - URI string `validate:"uri"` - Base64 string `validate:"base64"` - Contains string `validate:"contains=purpose"` - ContainsAny string `validate:"containsany=!@#$"` - Excludes string `validate:"excludes=text"` - ExcludesAll string `validate:"excludesall=!@#$"` - ExcludesRune string `validate:"excludesrune=☻"` - ISBN string `validate:"isbn"` - ISBN10 string `validate:"isbn10"` - ISBN13 string `validate:"isbn13"` - UUID string `validate:"uuid"` - UUID3 string `validate:"uuid3"` - UUID4 string `validate:"uuid4"` - UUID5 string `validate:"uuid5"` - ASCII string `validate:"ascii"` - PrintableASCII string `validate:"printascii"` - MultiByte string `validate:"multibyte"` - DataURI string `validate:"datauri"` - Latitude string `validate:"latitude"` - Longitude string `validate:"longitude"` - SSN string `validate:"ssn"` - IP string `validate:"ip"` - IPv4 string `validate:"ipv4"` - IPv6 string `validate:"ipv6"` - CIDR string `validate:"cidr"` - CIDRv4 string `validate:"cidrv4"` - CIDRv6 string `validate:"cidrv6"` - TCPAddr string `validate:"tcp_addr"` - TCPAddrv4 string `validate:"tcp4_addr"` - TCPAddrv6 string `validate:"tcp6_addr"` - UDPAddr string `validate:"udp_addr"` - UDPAddrv4 string `validate:"udp4_addr"` - UDPAddrv6 string `validate:"udp6_addr"` - IPAddr string `validate:"ip_addr"` - IPAddrv4 string `validate:"ip4_addr"` - IPAddrv6 string `validate:"ip6_addr"` - UinxAddr string `validate:"unix_addr"` // can't fail from within Go's net package currently, but maybe in the future - MAC string `validate:"mac"` - IsColor string `validate:"iscolor"` - StrPtrMinLen *string `validate:"min=10"` - StrPtrMaxLen *string `validate:"max=1"` - StrPtrLen *string `validate:"len=2"` - StrPtrLt *string `validate:"lt=1"` - StrPtrLte *string `validate:"lte=1"` - StrPtrGt *string `validate:"gt=10"` - StrPtrGte *string `validate:"gte=10"` - OneOfString string `validate:"oneof=red green"` - OneOfInt int `validate:"oneof=5 63"` - UniqueSlice []string `validate:"unique"` - UniqueArray [3]string `validate:"unique"` - UniqueMap map[string]string `validate:"unique"` - } - - var test Test - - test.Inner.EqCSFieldString = "1234" - test.Inner.GtCSFieldString = "1234" - test.Inner.GteCSFieldString = "1234" - - test.MaxString = "1234" - test.MaxNumber = 2000 - test.MaxMultiple = make([]string, 9) - - test.LtString = "1234" - test.LtNumber = 6 - test.LtMultiple = make([]string, 3) - test.LtTime = time.Now().Add(time.Hour * 24) - - test.LteString = "1234" - test.LteNumber = 6 - test.LteMultiple = make([]string, 3) - test.LteTime = time.Now().Add(time.Hour * 24) - - test.LtFieldString = "12345" - test.LteFieldString = "12345" - - test.LtCSFieldString = "1234" - test.LteCSFieldString = "1234" - - test.AlphaString = "abc3" - test.AlphanumString = "abc3!" - test.NumericString = "12E.00" - test.NumberString = "12E" - - test.Excludes = "this is some test text" - test.ExcludesAll = "This is Great!" - test.ExcludesRune = "Love it ☻" - - test.ASCII = "カタカナ" - test.PrintableASCII = "カタカナ" - - test.MultiByte = "1234feerf" - - s := "toolong" - test.StrPtrMaxLen = &s - test.StrPtrLen = &s - - test.UniqueSlice = []string{"1234", "1234"} - test.UniqueMap = map[string]string{"key1": "1234", "key2": "1234"} - - err = validate.Struct(test) - NotEqual(t, err, nil) - - errs, ok := err.(validator.ValidationErrors) - Equal(t, ok, true) - - tests := []struct { - ns string - expected string - }{ - { - ns: "Test.IsColor", - expected: "IsColor должен быть цветом", - }, - { - ns: "Test.MAC", - expected: "MAC должен содержать MAC адрес", - }, - { - ns: "Test.IPAddr", - expected: "IPAddr должен быть распознаваемым IP адресом", - }, - { - ns: "Test.IPAddrv4", - expected: "IPAddrv4 должен быть распознаваемым IPv4 адресом", - }, - { - ns: "Test.IPAddrv6", - expected: "IPAddrv6 должен быть распознаваемым IPv6 адресом", - }, - { - ns: "Test.UDPAddr", - expected: "UDPAddr должен быть UDP адресом", - }, - { - ns: "Test.UDPAddrv4", - expected: "UDPAddrv4 должен быть IPv4 UDP адресом", - }, - { - ns: "Test.UDPAddrv6", - expected: "UDPAddrv6 должен быть IPv6 UDP адресом", - }, - { - ns: "Test.TCPAddr", - expected: "TCPAddr должен быть TCP адресом", - }, - { - ns: "Test.TCPAddrv4", - expected: "TCPAddrv4 должен быть IPv4 TCP адресом", - }, - { - ns: "Test.TCPAddrv6", - expected: "TCPAddrv6 должен быть IPv6 TCP адресом", - }, - { - ns: "Test.CIDR", - expected: "CIDR должен содержать CIDR обозначения", - }, - { - ns: "Test.CIDRv4", - expected: "CIDRv4 должен содержать CIDR обозначения для IPv4 адреса", - }, - { - ns: "Test.CIDRv6", - expected: "CIDRv6 должен содержать CIDR обозначения для IPv6 адреса", - }, - { - ns: "Test.SSN", - expected: "SSN должен быть SSN номером", - }, - { - ns: "Test.IP", - expected: "IP должен быть IP адресом", - }, - { - ns: "Test.IPv4", - expected: "IPv4 должен быть IPv4 адресом", - }, - { - ns: "Test.IPv6", - expected: "IPv6 должен быть IPv6 адресом", - }, - { - ns: "Test.DataURI", - expected: "DataURI должен содержать Data URI", - }, - { - ns: "Test.Latitude", - expected: "Latitude должен содержать координаты широты", - }, - { - ns: "Test.Longitude", - expected: "Longitude должен содержать координаты долготы", - }, - { - ns: "Test.MultiByte", - expected: "MultiByte должен содержать мультибайтные символы", - }, - { - ns: "Test.ASCII", - expected: "ASCII должен содержать только ascii символы", - }, - { - ns: "Test.PrintableASCII", - expected: "PrintableASCII должен содержать только доступные для печати ascii символы", - }, - { - ns: "Test.UUID", - expected: "UUID должен быть UUID", - }, - { - ns: "Test.UUID3", - expected: "UUID3 должен быть UUID 3 версии", - }, - { - ns: "Test.UUID4", - expected: "UUID4 должен быть UUID 4 версии", - }, - { - ns: "Test.UUID5", - expected: "UUID5 должен быть UUID 5 версии", - }, - { - ns: "Test.ISBN", - expected: "ISBN должен быть ISBN номером", - }, - { - ns: "Test.ISBN10", - expected: "ISBN10 должен быть ISBN-10 номером", - }, - { - ns: "Test.ISBN13", - expected: "ISBN13 должен быть ISBN-13 номером", - }, - { - ns: "Test.Excludes", - expected: "Excludes не должен содержать текст 'text'", - }, - { - ns: "Test.ExcludesAll", - expected: "ExcludesAll не должен содержать символы '!@#$'", - }, - { - ns: "Test.ExcludesRune", - expected: "ExcludesRune не должен содержать '☻'", - }, - { - ns: "Test.ContainsAny", - expected: "ContainsAny должен содержать минимум один из символов '!@#$'", - }, - { - ns: "Test.Contains", - expected: "Contains должен содержать текст 'purpose'", - }, - { - ns: "Test.Base64", - expected: "Base64 должен быть Base64 строкой", - }, - { - ns: "Test.Email", - expected: "Email должен быть email адресом", - }, - { - ns: "Test.URL", - expected: "URL должен быть URL", - }, - { - ns: "Test.URI", - expected: "URI должен быть URI", - }, - { - ns: "Test.RGBColorString", - expected: "RGBColorString должен быть RGB цветом", - }, - { - ns: "Test.RGBAColorString", - expected: "RGBAColorString должен быть RGBA цветом", - }, - { - ns: "Test.HSLColorString", - expected: "HSLColorString должен быть HSL цветом", - }, - { - ns: "Test.HSLAColorString", - expected: "HSLAColorString должен быть HSLA цветом", - }, - { - ns: "Test.HexadecimalString", - expected: "HexadecimalString должен быть шестнадцатеричной строкой", - }, - { - ns: "Test.HexColorString", - expected: "HexColorString должен быть HEX цветом", - }, - { - ns: "Test.NumberString", - expected: "NumberString должен быть цифрой", - }, - { - ns: "Test.NumericString", - expected: "NumericString должен быть цифровым значением", - }, - { - ns: "Test.AlphanumString", - expected: "AlphanumString должен содержать только буквы и цифры", - }, - { - ns: "Test.AlphaString", - expected: "AlphaString должен содержать только буквы", - }, - { - ns: "Test.LtFieldString", - expected: "LtFieldString должен быть менее MaxString", - }, - { - ns: "Test.LteFieldString", - expected: "LteFieldString должен быть менее или равен MaxString", - }, - { - ns: "Test.GtFieldString", - expected: "GtFieldString должен быть больше MaxString", - }, - { - ns: "Test.GteFieldString", - expected: "GteFieldString должен быть больше или равен MaxString", - }, - { - ns: "Test.NeFieldString", - expected: "NeFieldString не должен быть равен EqFieldString", - }, - { - ns: "Test.LtCSFieldString", - expected: "LtCSFieldString должен быть менее Inner.LtCSFieldString", - }, - { - ns: "Test.LteCSFieldString", - expected: "LteCSFieldString должен быть менее или равен Inner.LteCSFieldString", - }, - { - ns: "Test.GtCSFieldString", - expected: "GtCSFieldString должен быть больше Inner.GtCSFieldString", - }, - { - ns: "Test.GteCSFieldString", - expected: "GteCSFieldString должен быть больше или равен Inner.GteCSFieldString", - }, - { - ns: "Test.NeCSFieldString", - expected: "NeCSFieldString не должен быть равен Inner.NeCSFieldString", - }, - { - ns: "Test.EqCSFieldString", - expected: "EqCSFieldString должен быть равен Inner.EqCSFieldString", - }, - { - ns: "Test.EqFieldString", - expected: "EqFieldString должен быть равен MaxString", - }, - { - ns: "Test.GteString", - expected: "GteString должен содержать минимум 3 символы", - }, - { - ns: "Test.GteNumber", - expected: "GteNumber должен быть больше или равно 5.56", - }, - { - ns: "Test.GteMultiple", - expected: "GteMultiple должен содержать минимум 2 элементы", - }, - { - ns: "Test.GteTime", - expected: "GteTime должна быть позже или равна текущему моменту", - }, - { - ns: "Test.GtString", - expected: "GtString должен быть длиннее 3 символы", - }, - { - ns: "Test.GtNumber", - expected: "GtNumber должен быть больше 5.56", - }, - { - ns: "Test.GtMultiple", - expected: "GtMultiple должен содержать более 2 элементы", - }, - { - ns: "Test.GtTime", - expected: "GtTime должна быть позже текущего момента", - }, - { - ns: "Test.LteString", - expected: "LteString должен содержать максимум 3 символы", - }, - { - ns: "Test.LteNumber", - expected: "LteNumber должен быть менее или равен 5.56", - }, - { - ns: "Test.LteMultiple", - expected: "LteMultiple должен содержать максимум 2 элементы", - }, - { - ns: "Test.LteTime", - expected: "LteTime must be less than or equal to the current Date & Time", - }, - { - ns: "Test.LtString", - expected: "LtString должен иметь менее 3 символы", - }, - { - ns: "Test.LtNumber", - expected: "LtNumber должен быть менее 5.56", - }, - { - ns: "Test.LtMultiple", - expected: "LtMultiple должен содержать менее 2 элементы", - }, - { - ns: "Test.LtTime", - expected: "LtTime must be less than the current Date & Time", - }, - { - ns: "Test.NeString", - expected: "NeString должен быть не равен ", - }, - { - ns: "Test.NeNumber", - expected: "NeNumber должен быть не равен 0.00", - }, - { - ns: "Test.NeMultiple", - expected: "NeMultiple должен быть не равен 0", - }, - { - ns: "Test.EqString", - expected: "EqString не равен 3", - }, - { - ns: "Test.EqNumber", - expected: "EqNumber не равен 2.33", - }, - { - ns: "Test.EqMultiple", - expected: "EqMultiple не равен 7", - }, - { - ns: "Test.MaxString", - expected: "MaxString должен содержать максимум 3 символы", - }, - { - ns: "Test.MaxNumber", - expected: "MaxNumber должен быть меньше или равно 1,113.00", - }, - { - ns: "Test.MaxMultiple", - expected: "MaxMultiple должен содержать максимум 7 элементы", - }, - { - ns: "Test.MinString", - expected: "MinString должен содержать минимум 1 символ", - }, - { - ns: "Test.MinNumber", - expected: "MinNumber должен быть больше или равно 1,113.00", - }, - { - ns: "Test.MinMultiple", - expected: "MinMultiple должен содержать минимум 7 элементы", - }, - { - ns: "Test.LenString", - expected: "LenString должен быть длиной в 1 символ", - }, - { - ns: "Test.LenNumber", - expected: "LenNumber должен быть равен 1,113.00", - }, - { - ns: "Test.LenMultiple", - expected: "LenMultiple должен содержать 7 элементы", - }, - { - ns: "Test.RequiredString", - expected: "RequiredString обязательное поле", - }, - { - ns: "Test.RequiredNumber", - expected: "RequiredNumber обязательное поле", - }, - { - ns: "Test.RequiredMultiple", - expected: "RequiredMultiple обязательное поле", - }, - { - ns: "Test.StrPtrMinLen", - expected: "StrPtrMinLen должен содержать минимум 10 символы", - }, - { - ns: "Test.StrPtrMaxLen", - expected: "StrPtrMaxLen должен содержать максимум 1 символ", - }, - { - ns: "Test.StrPtrLen", - expected: "StrPtrLen должен быть длиной в 2 символы", - }, - { - ns: "Test.StrPtrLt", - expected: "StrPtrLt должен иметь менее 1 символ", - }, - { - ns: "Test.StrPtrLte", - expected: "StrPtrLte должен содержать максимум 1 символ", - }, - { - ns: "Test.StrPtrGt", - expected: "StrPtrGt должен быть длиннее 10 символы", - }, - { - ns: "Test.StrPtrGte", - expected: "StrPtrGte должен содержать минимум 10 символы", - }, - { - ns: "Test.OneOfString", - expected: "OneOfString должен быть одним из [red green]", - }, - { - ns: "Test.OneOfInt", - expected: "OneOfInt должен быть одним из [5 63]", - }, - { - ns: "Test.UniqueSlice", - expected: "UniqueSlice должен содержать уникальные значения", - }, - { - ns: "Test.UniqueArray", - expected: "UniqueArray должен содержать уникальные значения", - }, - { - ns: "Test.UniqueMap", - expected: "UniqueMap должен содержать уникальные значения", - }, - } - - for _, tt := range tests { - - var fe validator.FieldError - - for _, e := range errs { - if tt.ns == e.Namespace() { - fe = e - break - } - } - - log.Println(fe) - - NotEqual(t, fe, nil) - Equal(t, tt.expected, fe.Translate(trans)) - } - -} diff --git a/go-playground/validator/v10/translations/tr/tr.go b/go-playground/validator/v10/translations/tr/tr.go deleted file mode 100644 index 2c3d773..0000000 --- a/go-playground/validator/v10/translations/tr/tr.go +++ /dev/null @@ -1,1370 +0,0 @@ -package tr - -import ( - "fmt" - "log" - "reflect" - "strconv" - "strings" - "time" - - "git.ningdatech.com/ningda/gin_valid/go-playground/locales" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -// RegisterDefaultTranslations registers a set of default translations -// for all built in tag's in validator; you may add your own as desired. -func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (err error) { - - translations := []struct { - tag string - translation string - override bool - customRegisFunc validator.RegisterTranslationsFunc - customTransFunc validator.TranslationFunc - }{ - { - tag: "required", - translation: "{0} zorunlu bir alandır", - override: false, - }, - { - tag: "len", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("len-string", "{0} uzunluğu {1} olmalıdır", false); err != nil { - return - } - - if err = ut.AddCardinal("len-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("len-string-character", "{0} karakter", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("len-number", "{0}, {1} değerine eşit olmalıdır", false); err != nil { - return - } - - if err = ut.Add("len-items", "{0}, {1} içermelidir", false); err != nil { - return - } - if err = ut.AddCardinal("len-items-item", "{0} öğe", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("len-items-item", "{0} öğe", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("len-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("len-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-items", fe.Field(), c) - - default: - t, err = ut.T("len-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "min", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("min-string", "{0} en az {1} uzunluğunda olmalıdır", false); err != nil { - return - } - - if err = ut.AddCardinal("min-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("min-string-character", "{0} karakter", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("min-number", "{0}, {1} veya daha büyük olmalıdır", false); err != nil { - return - } - - if err = ut.Add("min-items", "{0} en az {1} içermelidir", false); err != nil { - return - } - if err = ut.AddCardinal("min-items-item", "{0} öğe", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("min-items-item", "{0} öğe", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("min-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("min-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-items", fe.Field(), c) - - default: - t, err = ut.T("min-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "max", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("max-string", "{0} uzunluğu en fazla {1} olmalıdır", false); err != nil { - return - } - - if err = ut.AddCardinal("max-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("max-string-character", "{0} karakter", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("max-number", "{0}, {1} veya daha az olmalıdır", false); err != nil { - return - } - - if err = ut.Add("max-items", "{0} maksimum {1} içermelidir", false); err != nil { - return - } - if err = ut.AddCardinal("max-items-item", "{0} öğe", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("max-items-item", "{0} öğe", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("max-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("max-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-items", fe.Field(), c) - - default: - t, err = ut.T("max-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eq", - translation: "{0}, {1} değerine eşit değil", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ne", - translation: "{0}, {1} değerine eşit olmamalıdır", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lt-string", "{0}, {1} uzunluğundan daha az olmalıdır", false); err != nil { - return - } - - if err = ut.AddCardinal("lt-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lt-string-character", "{0} karakter", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-number", "{0}, {1} değerinden küçük olmalıdır", false); err != nil { - return - } - - if err = ut.Add("lt-items", "{0}, {1}den daha az içermelidir", false); err != nil { - return - } - - if err = ut.AddCardinal("lt-items-item", "{0} öğe", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lt-items-item", "{0} öğe", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-datetime", "{0} geçerli Tarih ve Saatten daha az olmalıdır", false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lte-string", "{0} en fazla {1} uzunluğunda olmalıdır", false); err != nil { - return - } - - if err = ut.AddCardinal("lte-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lte-string-character", "{0} karakter", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-number", "{0}, {1} veya daha az olmalıdır", false); err != nil { - return - } - - if err = ut.Add("lte-items", "{0}, maksimum {1} içermelidir", false); err != nil { - return - } - - if err = ut.AddCardinal("lte-items-item", "{0} öğe", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("lte-items-item", "{0} öğe", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-datetime", "{0} geçerli Tarih ve Saate eşit veya daha küçük olmalıdır", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("lte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gt-string", "{0}, {1} uzunluğundan fazla olmalıdır", false); err != nil { - return - } - - if err = ut.AddCardinal("gt-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gt-string-character", "{0} karakter", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-number", "{0}, {1} değerinden büyük olmalıdır", false); err != nil { - return - } - - if err = ut.Add("gt-items", "{0}, {1}den daha fazla içermelidir", false); err != nil { - return - } - - if err = ut.AddCardinal("gt-items-item", "{0} öğe", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gt-items-item", "{0} öğe", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-datetime", "{0} geçerli Tarih ve Saatten büyük olmalıdır", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gt-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gte-string", "{0} en az {1} uzunluğunda olmalıdır", false); err != nil { - return - } - - if err = ut.AddCardinal("gte-string-character", "{0} karakter", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gte-string-character", "{0} karakter", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-number", "{0}, {1} veya daha büyük olmalıdır", false); err != nil { - return - } - - if err = ut.Add("gte-items", "{0} en az {1} içermelidir", false); err != nil { - return - } - - if err = ut.AddCardinal("gte-items-item", "{0} öğe", locales.PluralRuleOne, false); err != nil { - return - } - - if err = ut.AddCardinal("gte-items-item", "{0} öğe", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-datetime", "{0} geçerli Tarih ve Saatten büyük veya ona eşit olmalıdır", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s' cannot be used on a struct type", fe.Tag()) - goto END - } - - t, err = ut.T("gte-datetime", fe.Field()) - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("warning: error translating FieldError: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqfield", - translation: "{0}, {1} değerine eşit olmalıdır", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqcsfield", - translation: "{0}, {1} değerine eşit olmalıdır", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "necsfield", - translation: "{0}, {1} değerine eşit olmamalıdır", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtcsfield", - translation: "{0}, {1} değerinden büyük olmalıdır", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtecsfield", - translation: "{0}, {1} değerinden küçük veya ona eşit olmalıdır", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltcsfield", - translation: "{0}, {1} değerinden küçük olmalıdır", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltecsfield", - translation: "{0}, {1} değerinden küçük veya ona eşit olmalıdır", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "nefield", - translation: "{0}, {1} değerine eşit olmamalıdır", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtfield", - translation: "{0}, {1} değerinden büyük olmalıdır", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtefield", - translation: "{0}, {1} değerinden büyük veya ona eşit olmalıdır", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltfield", - translation: "{0}, {1} değerinden küçük olmalıdır", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltefield", - translation: "{0}, {1} değerinden küçük veya ona eşit olmalıdır", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "alpha", - translation: "{0} yalnızca alfabetik karakterler içerebilir", - override: false, - }, - { - tag: "alphanum", - translation: "{0} yalnızca alfanümerik karakterler içerebilir", - override: false, - }, - { - tag: "numeric", - translation: "{0} geçerli bir sayısal değer olmalıdır", - override: false, - }, - { - tag: "number", - translation: "{0} geçerli bir sayı olmalıdır", - override: false, - }, - { - tag: "hexadecimal", - translation: "{0} geçerli bir onaltılık olmalıdır", - override: false, - }, - { - tag: "hexcolor", - translation: "{0} geçerli bir HEX rengi olmalıdır", - override: false, - }, - { - tag: "rgb", - translation: "{0} geçerli bir RGB rengi olmalıdır", - override: false, - }, - { - tag: "rgba", - translation: "{0} geçerli bir RGBA rengi olmalıdır", - override: false, - }, - { - tag: "hsl", - translation: "{0} geçerli bir HSL rengi olmalıdır", - override: false, - }, - { - tag: "hsla", - translation: "{0} geçerli bir HSLA rengi olmalıdır", - override: false, - }, - { - tag: "email", - translation: "{0} geçerli bir e-posta adresi olmalıdır", - override: false, - }, - { - tag: "url", - translation: "{0} geçerli bir URL olmalıdır", - override: false, - }, - { - tag: "uri", - translation: "{0} geçerli bir URI olmalıdır", - override: false, - }, - { - tag: "base64", - translation: "{0} geçerli bir Base64 karakter dizesi olmalıdır", - override: false, - }, - { - tag: "contains", - translation: "{0}, '{1}' metnini içermelidir", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "containsany", - translation: "{0}, '{1}' karakterlerinden en az birini içermelidir", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludes", - translation: "{0}, '{1}' metnini içeremez", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesall", - translation: "{0}, '{1}' karakterlerinden hiçbirini içeremez", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesrune", - translation: "{0}, '{1}' ifadesini içeremez", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "isbn", - translation: "{0} geçerli bir ISBN numarası olmalıdır", - override: false, - }, - { - tag: "isbn10", - translation: "{0} geçerli bir ISBN-10 numarası olmalıdır", - override: false, - }, - { - tag: "isbn13", - translation: "{0} geçerli bir ISBN-13 numarası olmalıdır", - override: false, - }, - { - tag: "uuid", - translation: "{0} geçerli bir UUID olmalıdır", - override: false, - }, - { - tag: "uuid3", - translation: "{0} geçerli bir sürüm 3 UUID olmalıdır", - override: false, - }, - { - tag: "uuid4", - translation: "{0} geçerli bir sürüm 4 UUID olmalıdır", - override: false, - }, - { - tag: "uuid5", - translation: "{0} geçerli bir sürüm 5 UUID olmalıdır", - override: false, - }, - { - tag: "ascii", - translation: "{0} yalnızca ascii karakterler içermelidir", - override: false, - }, - { - tag: "printascii", - translation: "{0} yalnızca yazdırılabilir ascii karakterleri içermelidir", - override: false, - }, - { - tag: "multibyte", - translation: "{0} çok baytlı karakterler içermelidir", - override: false, - }, - { - tag: "datauri", - translation: "{0} geçerli bir Veri URI içermelidir", - override: false, - }, - { - tag: "latitude", - translation: "{0} geçerli bir enlem koordinatı içermelidir", - override: false, - }, - { - tag: "longitude", - translation: "{0} geçerli bir boylam koordinatı içermelidir", - override: false, - }, - { - tag: "ssn", - translation: "{0} geçerli bir SSN numarası olmalıdır", - override: false, - }, - { - tag: "ipv4", - translation: "{0} geçerli bir IPv4 adresi olmalıdır", - override: false, - }, - { - tag: "ipv6", - translation: "{0} geçerli bir IPv6 adresi olmalıdır", - override: false, - }, - { - tag: "ip", - translation: "{0} geçerli bir IP adresi olmalıdır", - override: false, - }, - { - tag: "cidr", - translation: "{0} geçerli bir CIDR gösterimi içermelidir", - override: false, - }, - { - tag: "cidrv4", - translation: "{0} bir IPv4 adresi için geçerli bir CIDR gösterimi içermelidir", - override: false, - }, - { - tag: "cidrv6", - translation: "{0} bir IPv6 adresi için geçerli bir CIDR gösterimi içermelidir", - override: false, - }, - { - tag: "tcp_addr", - translation: "{0} geçerli bir TCP adresi olmalıdır", - override: false, - }, - { - tag: "tcp4_addr", - translation: "{0} geçerli bir IPv4 TCP adresi olmalıdır", - override: false, - }, - { - tag: "tcp6_addr", - translation: "{0} geçerli bir IPv6 TCP adresi olmalıdır", - override: false, - }, - { - tag: "udp_addr", - translation: "{0} geçerli bir UDP adresi olmalıdır", - override: false, - }, - { - tag: "udp4_addr", - translation: "{0} geçerli bir IPv4 UDP adresi olmalıdır", - override: false, - }, - { - tag: "udp6_addr", - translation: "{0} geçerli bir IPv6 UDP adresi olmalıdır", - override: false, - }, - { - tag: "ip_addr", - translation: "{0} çözülebilir bir IP adresi olmalıdır", - override: false, - }, - { - tag: "ip4_addr", - translation: "{0} çözülebilir bir IPv4 adresi olmalıdır", - override: false, - }, - { - tag: "ip6_addr", - translation: "{0} çözülebilir bir IPv6 adresi olmalıdır", - override: false, - }, - { - tag: "unix_addr", - translation: "{0} çözülebilir bir UNIX adresi olmalıdır", - override: false, - }, - { - tag: "mac", - translation: "{0} geçerli bir MAC adresi içermelidir", - override: false, - }, - { - tag: "unique", - translation: "{0} benzersiz değerler içermelidir", - override: false, - }, - { - tag: "iscolor", - translation: "{0} geçerli bir renk olmalıdır", - override: false, - }, - { - tag: "oneof", - translation: "{0}, [{1}]'dan biri olmalıdır", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - s, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - return s - }, - }, - } - - for _, t := range translations { - - if t.customTransFunc != nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, t.customTransFunc) - - } else if t.customTransFunc != nil && t.customRegisFunc == nil { - - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), t.customTransFunc) - - } else if t.customTransFunc == nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, translateFunc) - - } else { - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), translateFunc) - } - - if err != nil { - return - } - } - - return -} - -func registrationFunc(tag string, translation string, override bool) validator.RegisterTranslationsFunc { - - return func(ut ut.Translator) (err error) { - - if err = ut.Add(tag, translation, override); err != nil { - return - } - - return - - } - -} - -func translateFunc(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field()) - if err != nil { - log.Printf("warning: error translating FieldError: %#v", fe) - return fe.(error).Error() - } - - return t -} diff --git a/go-playground/validator/v10/translations/tr/tr_test.go b/go-playground/validator/v10/translations/tr/tr_test.go deleted file mode 100644 index f524d04..0000000 --- a/go-playground/validator/v10/translations/tr/tr_test.go +++ /dev/null @@ -1,652 +0,0 @@ -package tr - -import ( - "testing" - "time" - - . "git.ningdatech.com/ningda/gin_valid/go-playground/assert/v2" - turkish "git.ningdatech.com/ningda/gin_valid/go-playground/locales/tr" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -func TestTranslations(t *testing.T) { - - tr := turkish.New() - uni := ut.New(tr, tr) - trans, _ := uni.GetTranslator("tr") - - validate := validator.New() - - err := RegisterDefaultTranslations(validate, trans) - Equal(t, err, nil) - - type Inner struct { - EqCSFieldString string - NeCSFieldString string - GtCSFieldString string - GteCSFieldString string - LtCSFieldString string - LteCSFieldString string - } - - type Test struct { - Inner Inner - RequiredString string `validate:"required"` - RequiredNumber int `validate:"required"` - RequiredMultiple []string `validate:"required"` - LenString string `validate:"len=1"` - LenNumber float64 `validate:"len=1113.00"` - LenMultiple []string `validate:"len=7"` - MinString string `validate:"min=1"` - MinNumber float64 `validate:"min=1113.00"` - MinMultiple []string `validate:"min=7"` - MaxString string `validate:"max=3"` - MaxNumber float64 `validate:"max=1113.00"` - MaxMultiple []string `validate:"max=7"` - EqString string `validate:"eq=3"` - EqNumber float64 `validate:"eq=2.33"` - EqMultiple []string `validate:"eq=7"` - NeString string `validate:"ne="` - NeNumber float64 `validate:"ne=0.00"` - NeMultiple []string `validate:"ne=0"` - LtString string `validate:"lt=3"` - LtNumber float64 `validate:"lt=5.56"` - LtMultiple []string `validate:"lt=2"` - LtTime time.Time `validate:"lt"` - LteString string `validate:"lte=3"` - LteNumber float64 `validate:"lte=5.56"` - LteMultiple []string `validate:"lte=2"` - LteTime time.Time `validate:"lte"` - GtString string `validate:"gt=3"` - GtNumber float64 `validate:"gt=5.56"` - GtMultiple []string `validate:"gt=2"` - GtTime time.Time `validate:"gt"` - GteString string `validate:"gte=3"` - GteNumber float64 `validate:"gte=5.56"` - GteMultiple []string `validate:"gte=2"` - GteTime time.Time `validate:"gte"` - EqFieldString string `validate:"eqfield=MaxString"` - EqCSFieldString string `validate:"eqcsfield=Inner.EqCSFieldString"` - NeCSFieldString string `validate:"necsfield=Inner.NeCSFieldString"` - GtCSFieldString string `validate:"gtcsfield=Inner.GtCSFieldString"` - GteCSFieldString string `validate:"gtecsfield=Inner.GteCSFieldString"` - LtCSFieldString string `validate:"ltcsfield=Inner.LtCSFieldString"` - LteCSFieldString string `validate:"ltecsfield=Inner.LteCSFieldString"` - NeFieldString string `validate:"nefield=EqFieldString"` - GtFieldString string `validate:"gtfield=MaxString"` - GteFieldString string `validate:"gtefield=MaxString"` - LtFieldString string `validate:"ltfield=MaxString"` - LteFieldString string `validate:"ltefield=MaxString"` - AlphaString string `validate:"alpha"` - AlphanumString string `validate:"alphanum"` - NumericString string `validate:"numeric"` - NumberString string `validate:"number"` - HexadecimalString string `validate:"hexadecimal"` - HexColorString string `validate:"hexcolor"` - RGBColorString string `validate:"rgb"` - RGBAColorString string `validate:"rgba"` - HSLColorString string `validate:"hsl"` - HSLAColorString string `validate:"hsla"` - Email string `validate:"email"` - URL string `validate:"url"` - URI string `validate:"uri"` - Base64 string `validate:"base64"` - Contains string `validate:"contains=purpose"` - ContainsAny string `validate:"containsany=!@#$"` - Excludes string `validate:"excludes=text"` - ExcludesAll string `validate:"excludesall=!@#$"` - ExcludesRune string `validate:"excludesrune=☻"` - ISBN string `validate:"isbn"` - ISBN10 string `validate:"isbn10"` - ISBN13 string `validate:"isbn13"` - UUID string `validate:"uuid"` - UUID3 string `validate:"uuid3"` - UUID4 string `validate:"uuid4"` - UUID5 string `validate:"uuid5"` - ASCII string `validate:"ascii"` - PrintableASCII string `validate:"printascii"` - MultiByte string `validate:"multibyte"` - DataURI string `validate:"datauri"` - Latitude string `validate:"latitude"` - Longitude string `validate:"longitude"` - SSN string `validate:"ssn"` - IP string `validate:"ip"` - IPv4 string `validate:"ipv4"` - IPv6 string `validate:"ipv6"` - CIDR string `validate:"cidr"` - CIDRv4 string `validate:"cidrv4"` - CIDRv6 string `validate:"cidrv6"` - TCPAddr string `validate:"tcp_addr"` - TCPAddrv4 string `validate:"tcp4_addr"` - TCPAddrv6 string `validate:"tcp6_addr"` - UDPAddr string `validate:"udp_addr"` - UDPAddrv4 string `validate:"udp4_addr"` - UDPAddrv6 string `validate:"udp6_addr"` - IPAddr string `validate:"ip_addr"` - IPAddrv4 string `validate:"ip4_addr"` - IPAddrv6 string `validate:"ip6_addr"` - UinxAddr string `validate:"unix_addr"` // can't fail from within Go's net package currently, but maybe in the future - MAC string `validate:"mac"` - IsColor string `validate:"iscolor"` - StrPtrMinLen *string `validate:"min=10"` - StrPtrMaxLen *string `validate:"max=1"` - StrPtrLen *string `validate:"len=2"` - StrPtrLt *string `validate:"lt=1"` - StrPtrLte *string `validate:"lte=1"` - StrPtrGt *string `validate:"gt=10"` - StrPtrGte *string `validate:"gte=10"` - OneOfString string `validate:"oneof=red green"` - OneOfInt int `validate:"oneof=5 63"` - UniqueSlice []string `validate:"unique"` - UniqueArray [3]string `validate:"unique"` - UniqueMap map[string]string `validate:"unique"` - } - - var test Test - - test.Inner.EqCSFieldString = "1234" - test.Inner.GtCSFieldString = "1234" - test.Inner.GteCSFieldString = "1234" - - test.MaxString = "1234" - test.MaxNumber = 2000 - test.MaxMultiple = make([]string, 9) - - test.LtString = "1234" - test.LtNumber = 6 - test.LtMultiple = make([]string, 3) - test.LtTime = time.Now().Add(time.Hour * 24) - - test.LteString = "1234" - test.LteNumber = 6 - test.LteMultiple = make([]string, 3) - test.LteTime = time.Now().Add(time.Hour * 24) - - test.LtFieldString = "12345" - test.LteFieldString = "12345" - - test.LtCSFieldString = "1234" - test.LteCSFieldString = "1234" - - test.AlphaString = "abc3" - test.AlphanumString = "abc3!" - test.NumericString = "12E.00" - test.NumberString = "12E" - - test.Excludes = "this is some test text" - test.ExcludesAll = "This is Great!" - test.ExcludesRune = "Love it ☻" - - test.ASCII = "カタカナ" - test.PrintableASCII = "カタカナ" - - test.MultiByte = "1234feerf" - - s := "toolong" - test.StrPtrMaxLen = &s - test.StrPtrLen = &s - - test.UniqueSlice = []string{"1234", "1234"} - test.UniqueMap = map[string]string{"key1": "1234", "key2": "1234"} - - err = validate.Struct(test) - NotEqual(t, err, nil) - - errs, ok := err.(validator.ValidationErrors) - Equal(t, ok, true) - - tests := []struct { - ns string - expected string - }{ - { - ns: "Test.IsColor", - expected: "IsColor geçerli bir renk olmalıdır", - }, - { - ns: "Test.MAC", - expected: "MAC geçerli bir MAC adresi içermelidir", - }, - { - ns: "Test.IPAddr", - expected: "IPAddr çözülebilir bir IP adresi olmalıdır", - }, - { - ns: "Test.IPAddrv4", - expected: "IPAddrv4 çözülebilir bir IPv4 adresi olmalıdır", - }, - { - ns: "Test.IPAddrv6", - expected: "IPAddrv6 çözülebilir bir IPv6 adresi olmalıdır", - }, - { - ns: "Test.UDPAddr", - expected: "UDPAddr geçerli bir UDP adresi olmalıdır", - }, - { - ns: "Test.UDPAddrv4", - expected: "UDPAddrv4 geçerli bir IPv4 UDP adresi olmalıdır", - }, - { - ns: "Test.UDPAddrv6", - expected: "UDPAddrv6 geçerli bir IPv6 UDP adresi olmalıdır", - }, - { - ns: "Test.TCPAddr", - expected: "TCPAddr geçerli bir TCP adresi olmalıdır", - }, - { - ns: "Test.TCPAddrv4", - expected: "TCPAddrv4 geçerli bir IPv4 TCP adresi olmalıdır", - }, - { - ns: "Test.TCPAddrv6", - expected: "TCPAddrv6 geçerli bir IPv6 TCP adresi olmalıdır", - }, - { - ns: "Test.CIDR", - expected: "CIDR geçerli bir CIDR gösterimi içermelidir", - }, - { - ns: "Test.CIDRv4", - expected: "CIDRv4 bir IPv4 adresi için geçerli bir CIDR gösterimi içermelidir", - }, - { - ns: "Test.CIDRv6", - expected: "CIDRv6 bir IPv6 adresi için geçerli bir CIDR gösterimi içermelidir", - }, - { - ns: "Test.SSN", - expected: "SSN geçerli bir SSN numarası olmalıdır", - }, - { - ns: "Test.IP", - expected: "IP geçerli bir IP adresi olmalıdır", - }, - { - ns: "Test.IPv4", - expected: "IPv4 geçerli bir IPv4 adresi olmalıdır", - }, - { - ns: "Test.IPv6", - expected: "IPv6 geçerli bir IPv6 adresi olmalıdır", - }, - { - ns: "Test.DataURI", - expected: "DataURI geçerli bir Veri URI içermelidir", - }, - { - ns: "Test.Latitude", - expected: "Latitude geçerli bir enlem koordinatı içermelidir", - }, - { - ns: "Test.Longitude", - expected: "Longitude geçerli bir boylam koordinatı içermelidir", - }, - { - ns: "Test.MultiByte", - expected: "MultiByte çok baytlı karakterler içermelidir", - }, - { - ns: "Test.ASCII", - expected: "ASCII yalnızca ascii karakterler içermelidir", - }, - { - ns: "Test.PrintableASCII", - expected: "PrintableASCII yalnızca yazdırılabilir ascii karakterleri içermelidir", - }, - { - ns: "Test.UUID", - expected: "UUID geçerli bir UUID olmalıdır", - }, - { - ns: "Test.UUID3", - expected: "UUID3 geçerli bir sürüm 3 UUID olmalıdır", - }, - { - ns: "Test.UUID4", - expected: "UUID4 geçerli bir sürüm 4 UUID olmalıdır", - }, - { - ns: "Test.UUID5", - expected: "UUID5 geçerli bir sürüm 5 UUID olmalıdır", - }, - { - ns: "Test.ISBN", - expected: "ISBN geçerli bir ISBN numarası olmalıdır", - }, - { - ns: "Test.ISBN10", - expected: "ISBN10 geçerli bir ISBN-10 numarası olmalıdır", - }, - { - ns: "Test.ISBN13", - expected: "ISBN13 geçerli bir ISBN-13 numarası olmalıdır", - }, - { - ns: "Test.Excludes", - expected: "Excludes, 'text' metnini içeremez", - }, - { - ns: "Test.ExcludesAll", - expected: "ExcludesAll, '!@#$' karakterlerinden hiçbirini içeremez", - }, - { - ns: "Test.ExcludesRune", - expected: "ExcludesRune, '☻' ifadesini içeremez", - }, - { - ns: "Test.ContainsAny", - expected: "ContainsAny, '!@#$' karakterlerinden en az birini içermelidir", - }, - { - ns: "Test.Contains", - expected: "Contains, 'purpose' metnini içermelidir", - }, - { - ns: "Test.Base64", - expected: "Base64 geçerli bir Base64 karakter dizesi olmalıdır", - }, - { - ns: "Test.Email", - expected: "Email geçerli bir e-posta adresi olmalıdır", - }, - { - ns: "Test.URL", - expected: "URL geçerli bir URL olmalıdır", - }, - { - ns: "Test.URI", - expected: "URI geçerli bir URI olmalıdır", - }, - { - ns: "Test.RGBColorString", - expected: "RGBColorString geçerli bir RGB rengi olmalıdır", - }, - { - ns: "Test.RGBAColorString", - expected: "RGBAColorString geçerli bir RGBA rengi olmalıdır", - }, - { - ns: "Test.HSLColorString", - expected: "HSLColorString geçerli bir HSL rengi olmalıdır", - }, - { - ns: "Test.HSLAColorString", - expected: "HSLAColorString geçerli bir HSLA rengi olmalıdır", - }, - { - ns: "Test.HexadecimalString", - expected: "HexadecimalString geçerli bir onaltılık olmalıdır", - }, - { - ns: "Test.HexColorString", - expected: "HexColorString geçerli bir HEX rengi olmalıdır", - }, - { - ns: "Test.NumberString", - expected: "NumberString geçerli bir sayı olmalıdır", - }, - { - ns: "Test.NumericString", - expected: "NumericString geçerli bir sayısal değer olmalıdır", - }, - { - ns: "Test.AlphanumString", - expected: "AlphanumString yalnızca alfanümerik karakterler içerebilir", - }, - { - ns: "Test.AlphaString", - expected: "AlphaString yalnızca alfabetik karakterler içerebilir", - }, - { - ns: "Test.LtFieldString", - expected: "LtFieldString, MaxString değerinden küçük olmalıdır", - }, - { - ns: "Test.LteFieldString", - expected: "LteFieldString, MaxString değerinden küçük veya ona eşit olmalıdır", - }, - { - ns: "Test.GtFieldString", - expected: "GtFieldString, MaxString değerinden büyük olmalıdır", - }, - { - ns: "Test.GteFieldString", - expected: "GteFieldString, MaxString değerinden büyük veya ona eşit olmalıdır", - }, - { - ns: "Test.NeFieldString", - expected: "NeFieldString, EqFieldString değerine eşit olmamalıdır", - }, - { - ns: "Test.LtCSFieldString", - expected: "LtCSFieldString, Inner.LtCSFieldString değerinden küçük olmalıdır", - }, - { - ns: "Test.LteCSFieldString", - expected: "LteCSFieldString, Inner.LteCSFieldString değerinden küçük veya ona eşit olmalıdır", - }, - { - ns: "Test.GtCSFieldString", - expected: "GtCSFieldString, Inner.GtCSFieldString değerinden büyük olmalıdır", - }, - { - ns: "Test.GteCSFieldString", - expected: "GteCSFieldString, Inner.GteCSFieldString değerinden küçük veya ona eşit olmalıdır", - }, - { - ns: "Test.NeCSFieldString", - expected: "NeCSFieldString, Inner.NeCSFieldString değerine eşit olmamalıdır", - }, - { - ns: "Test.EqCSFieldString", - expected: "EqCSFieldString, Inner.EqCSFieldString değerine eşit olmalıdır", - }, - { - ns: "Test.EqFieldString", - expected: "EqFieldString, MaxString değerine eşit olmalıdır", - }, - { - ns: "Test.GteString", - expected: "GteString en az 3 karakter uzunluğunda olmalıdır", - }, - { - ns: "Test.GteNumber", - expected: "GteNumber, 5,56 veya daha büyük olmalıdır", - }, - { - ns: "Test.GteMultiple", - expected: "GteMultiple en az 2 öğe içermelidir", - }, - { - ns: "Test.GteTime", - expected: "GteTime geçerli Tarih ve Saatten büyük veya ona eşit olmalıdır", - }, - { - ns: "Test.GtString", - expected: "GtString, 3 karakter uzunluğundan fazla olmalıdır", - }, - { - ns: "Test.GtNumber", - expected: "GtNumber, 5,56 değerinden büyük olmalıdır", - }, - { - ns: "Test.GtMultiple", - expected: "GtMultiple, 2 öğeden daha fazla içermelidir", - }, - { - ns: "Test.GtTime", - expected: "GtTime geçerli Tarih ve Saatten büyük olmalıdır", - }, - { - ns: "Test.LteString", - expected: "LteString en fazla 3 karakter uzunluğunda olmalıdır", - }, - { - ns: "Test.LteNumber", - expected: "LteNumber, 5,56 veya daha az olmalıdır", - }, - { - ns: "Test.LteMultiple", - expected: "LteMultiple, maksimum 2 öğe içermelidir", - }, - { - ns: "Test.LteTime", - expected: "LteTime geçerli Tarih ve Saate eşit veya daha küçük olmalıdır", - }, - { - ns: "Test.LtString", - expected: "LtString, 3 karakter uzunluğundan daha az olmalıdır", - }, - { - ns: "Test.LtNumber", - expected: "LtNumber, 5,56 değerinden küçük olmalıdır", - }, - { - ns: "Test.LtMultiple", - expected: "LtMultiple, 2 öğeden daha az içermelidir", - }, - { - ns: "Test.LtTime", - expected: "LtTime geçerli Tarih ve Saatten daha az olmalıdır", - }, - { - ns: "Test.NeString", - expected: "NeString, değerine eşit olmamalıdır", - }, - { - ns: "Test.NeNumber", - expected: "NeNumber, 0.00 değerine eşit olmamalıdır", - }, - { - ns: "Test.NeMultiple", - expected: "NeMultiple, 0 değerine eşit olmamalıdır", - }, - { - ns: "Test.EqString", - expected: "EqString, 3 değerine eşit değil", - }, - { - ns: "Test.EqNumber", - expected: "EqNumber, 2.33 değerine eşit değil", - }, - { - ns: "Test.EqMultiple", - expected: "EqMultiple, 7 değerine eşit değil", - }, - { - ns: "Test.MaxString", - expected: "MaxString uzunluğu en fazla 3 karakter olmalıdır", - }, - { - ns: "Test.MaxNumber", - expected: "MaxNumber, 1.113,00 veya daha az olmalıdır", - }, - { - ns: "Test.MaxMultiple", - expected: "MaxMultiple maksimum 7 öğe içermelidir", - }, - { - ns: "Test.MinString", - expected: "MinString en az 1 karakter uzunluğunda olmalıdır", - }, - { - ns: "Test.MinNumber", - expected: "MinNumber, 1.113,00 veya daha büyük olmalıdır", - }, - { - ns: "Test.MinMultiple", - expected: "MinMultiple en az 7 öğe içermelidir", - }, - { - ns: "Test.LenString", - expected: "LenString uzunluğu 1 karakter olmalıdır", - }, - { - ns: "Test.LenNumber", - expected: "LenNumber, 1.113,00 değerine eşit olmalıdır", - }, - { - ns: "Test.LenMultiple", - expected: "LenMultiple, 7 öğe içermelidir", - }, - { - ns: "Test.RequiredString", - expected: "RequiredString zorunlu bir alandır", - }, - { - ns: "Test.RequiredNumber", - expected: "RequiredNumber zorunlu bir alandır", - }, - { - ns: "Test.RequiredMultiple", - expected: "RequiredMultiple zorunlu bir alandır", - }, - { - ns: "Test.StrPtrMinLen", - expected: "StrPtrMinLen en az 10 karakter uzunluğunda olmalıdır", - }, - { - ns: "Test.StrPtrMaxLen", - expected: "StrPtrMaxLen uzunluğu en fazla 1 karakter olmalıdır", - }, - { - ns: "Test.StrPtrLen", - expected: "StrPtrLen uzunluğu 2 karakter olmalıdır", - }, - { - ns: "Test.StrPtrLt", - expected: "StrPtrLt, 1 karakter uzunluğundan daha az olmalıdır", - }, - { - ns: "Test.StrPtrLte", - expected: "StrPtrLte en fazla 1 karakter uzunluğunda olmalıdır", - }, - { - ns: "Test.StrPtrGt", - expected: "StrPtrGt, 10 karakter uzunluğundan fazla olmalıdır", - }, - { - ns: "Test.StrPtrGte", - expected: "StrPtrGte en az 10 karakter uzunluğunda olmalıdır", - }, - { - ns: "Test.OneOfString", - expected: "OneOfString, [red green]'dan biri olmalıdır", - }, - { - ns: "Test.OneOfInt", - expected: "OneOfInt, [5 63]'dan biri olmalıdır", - }, - { - ns: "Test.UniqueSlice", - expected: "UniqueSlice benzersiz değerler içermelidir", - }, - { - ns: "Test.UniqueArray", - expected: "UniqueArray benzersiz değerler içermelidir", - }, - { - ns: "Test.UniqueMap", - expected: "UniqueMap benzersiz değerler içermelidir", - }, - } - - for _, tt := range tests { - - var fe validator.FieldError - - for _, e := range errs { - if tt.ns == e.Namespace() { - fe = e - break - } - } - - NotEqual(t, fe, nil) - Equal(t, tt.expected, fe.Translate(trans)) - } - -} diff --git a/go-playground/validator/v10/translations/zh_tw/zh_tw.go b/go-playground/validator/v10/translations/zh_tw/zh_tw.go deleted file mode 100644 index 40dd9f5..0000000 --- a/go-playground/validator/v10/translations/zh_tw/zh_tw.go +++ /dev/null @@ -1,1373 +0,0 @@ -package zh_tw - -import ( - "fmt" - "log" - "reflect" - "strconv" - "strings" - "time" - - "git.ningdatech.com/ningda/gin_valid/go-playground/locales" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -// RegisterDefaultTranslations registers a set of default translations -// for all built in tag's in validator; you may add your own as desired. -func RegisterDefaultTranslations(v *validator.Validate, trans ut.Translator) (err error) { - - translations := []struct { - tag string - translation string - override bool - customRegisFunc validator.RegisterTranslationsFunc - customTransFunc validator.TranslationFunc - }{ - { - tag: "required", - translation: "{0}為必填欄位", - override: false, - }, - { - tag: "len", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("len-string", "{0}長度必須為{1}", false); err != nil { - return - } - - //if err = ut.AddCardinal("len-string-character", "{0}字元", locales.PluralRuleOne, false); err != nil { - // return - //} - - if err = ut.AddCardinal("len-string-character", "{0}個字元", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("len-number", "{0}必須等於{1}", false); err != nil { - return - } - - if err = ut.Add("len-items", "{0}必須包含{1}", false); err != nil { - return - } - //if err = ut.AddCardinal("len-items-item", "{0}項", locales.PluralRuleOne, false); err != nil { - // return - //} - - if err = ut.AddCardinal("len-items-item", "{0}項", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("len-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("len-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("len-items", fe.Field(), c) - - default: - t, err = ut.T("len-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("警告: 翻譯欄位錯誤: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "min", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("min-string", "{0}長度必須至少為{1}", false); err != nil { - return - } - - //if err = ut.AddCardinal("min-string-character", "{0}個字元", locales.PluralRuleOne, false); err != nil { - // return - //} - - if err = ut.AddCardinal("min-string-character", "{0}個字元", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("min-number", "{0}最小只能為{1}", false); err != nil { - return - } - - if err = ut.Add("min-items", "{0}必須至少包含{1}", false); err != nil { - return - } - //if err = ut.AddCardinal("min-items-item", "{0}項", locales.PluralRuleOne, false); err != nil { - // return - //} - - if err = ut.AddCardinal("min-items-item", "{0}項", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("min-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("min-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("min-items", fe.Field(), c) - - default: - t, err = ut.T("min-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("警告: 翻譯欄位錯誤: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "max", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("max-string", "{0}長度不能超過{1}", false); err != nil { - return - } - - //if err = ut.AddCardinal("max-string-character", "{0}個字元", locales.PluralRuleOne, false); err != nil { - // return - //} - - if err = ut.AddCardinal("max-string-character", "{0}個字元", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("max-number", "{0}必須小於或等於{1}", false); err != nil { - return - } - - if err = ut.Add("max-items", "{0}最多只能包含{1}", false); err != nil { - return - } - //if err = ut.AddCardinal("max-items-item", "{0}項", locales.PluralRuleOne, false); err != nil { - // return - //} - - if err = ut.AddCardinal("max-items-item", "{0}項", locales.PluralRuleOther, false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - - var digits uint64 - var kind reflect.Kind - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err := strconv.ParseFloat(fe.Param(), 64) - if err != nil { - goto END - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - c, err = ut.C("max-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - c, err = ut.C("max-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("max-items", fe.Field(), c) - - default: - t, err = ut.T("max-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("警告: 翻譯欄位錯誤: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eq", - translation: "{0}不等於{1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ne", - translation: "{0}不能等於{1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - fmt.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lt-string", "{0}長度必須小於{1}", false); err != nil { - return - } - - //if err = ut.AddCardinal("lt-string-character", "{0}個字元", locales.PluralRuleOne, false); err != nil { - // return - //} - - if err = ut.AddCardinal("lt-string-character", "{0}個字元", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-number", "{0}必須小於{1}", false); err != nil { - return - } - - if err = ut.Add("lt-items", "{0}必須包含少於{1}", false); err != nil { - return - } - - //if err = ut.AddCardinal("lt-items-item", "{0}項", locales.PluralRuleOne, false); err != nil { - // return - //} - - if err = ut.AddCardinal("lt-items-item", "{0}項", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lt-datetime", "{0}必須小於目前日期和時間", false); err != nil { - return - } - - return - - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s'不能用於struct類型.", fe.Tag()) - } else { - t, err = ut.T("lt-datetime", fe.Field()) - } - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("警告: 翻譯欄位錯誤: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "lte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("lte-string", "{0}長度不能超過{1}", false); err != nil { - return - } - - //if err = ut.AddCardinal("lte-string-character", "{0} character", locales.PluralRuleOne, false); err != nil { - // return - //} - - if err = ut.AddCardinal("lte-string-character", "{0}個字元", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-number", "{0}必須小於或等於{1}", false); err != nil { - return - } - - if err = ut.Add("lte-items", "{0}最多只能包含{1}", false); err != nil { - return - } - - //if err = ut.AddCardinal("lte-items-item", "{0} item", locales.PluralRuleOne, false); err != nil { - // return - //} - - if err = ut.AddCardinal("lte-items-item", "{0}項", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("lte-datetime", "{0}必須小於或等於目前日期和時間", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("lte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("lte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s'不能用於struct類型.", fe.Tag()) - } else { - t, err = ut.T("lte-datetime", fe.Field()) - } - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("lte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("警告: 翻譯欄位錯誤: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gt", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gt-string", "{0}長度必須大於{1}", false); err != nil { - return - } - - //if err = ut.AddCardinal("gt-string-character", "{0}個字元", locales.PluralRuleOne, false); err != nil { - // return - //} - - if err = ut.AddCardinal("gt-string-character", "{0}個字元", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-number", "{0}必須大於{1}", false); err != nil { - return - } - - if err = ut.Add("gt-items", "{0}必須大於{1}", false); err != nil { - return - } - - //if err = ut.AddCardinal("gt-items-item", "{0}項", locales.PluralRuleOne, false); err != nil { - // return - //} - - if err = ut.AddCardinal("gt-items-item", "{0}項", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gt-datetime", "{0}必須大於目前日期和時間", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - f64, err = strconv.ParseFloat(fe.Param(), 64) - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gt-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gt-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s'不能用於struct類型.", fe.Tag()) - } else { - t, err = ut.T("gt-datetime", fe.Field()) - } - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gt-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("警告: 翻譯欄位錯誤: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gte", - customRegisFunc: func(ut ut.Translator) (err error) { - - if err = ut.Add("gte-string", "{0}長度必須至少為{1}", false); err != nil { - return - } - - //if err = ut.AddCardinal("gte-string-character", "{0}個字元", locales.PluralRuleOne, false); err != nil { - // return - //} - - if err = ut.AddCardinal("gte-string-character", "{0}個字元", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-number", "{0}必須大於或等於{1}", false); err != nil { - return - } - - if err = ut.Add("gte-items", "{0}必須至少包含{1}", false); err != nil { - return - } - - //if err = ut.AddCardinal("gte-items-item", "{0}項", locales.PluralRuleOne, false); err != nil { - // return - //} - - if err = ut.AddCardinal("gte-items-item", "{0}項", locales.PluralRuleOther, false); err != nil { - return - } - - if err = ut.Add("gte-datetime", "{0}必須大於或等於目前日期和時間", false); err != nil { - return - } - - return - }, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - var err error - var t string - var f64 float64 - var digits uint64 - var kind reflect.Kind - - fn := func() (err error) { - - if idx := strings.Index(fe.Param(), "."); idx != -1 { - digits = uint64(len(fe.Param()[idx+1:])) - } - - f64, err = strconv.ParseFloat(fe.Param(), 64) - - return - } - - kind = fe.Kind() - if kind == reflect.Ptr { - kind = fe.Type().Elem().Kind() - } - - switch kind { - case reflect.String: - - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-string-character", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-string", fe.Field(), c) - - case reflect.Slice, reflect.Map, reflect.Array: - var c string - - err = fn() - if err != nil { - goto END - } - - c, err = ut.C("gte-items-item", f64, digits, ut.FmtNumber(f64, digits)) - if err != nil { - goto END - } - - t, err = ut.T("gte-items", fe.Field(), c) - - case reflect.Struct: - if fe.Type() != reflect.TypeOf(time.Time{}) { - err = fmt.Errorf("tag '%s'不能用於struct類型.", fe.Tag()) - } else { - t, err = ut.T("gte-datetime", fe.Field()) - } - - default: - err = fn() - if err != nil { - goto END - } - - t, err = ut.T("gte-number", fe.Field(), ut.FmtNumber(f64, digits)) - } - - END: - if err != nil { - fmt.Printf("警告: 翻譯欄位錯誤: %s", err) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqfield", - translation: "{0}必須等於{1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "eqcsfield", - translation: "{0}必須等於{1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "necsfield", - translation: "{0}不能等於{1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtcsfield", - translation: "{0}必須大於{1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtecsfield", - translation: "{0}必須大於或等於{1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltcsfield", - translation: "{0}必須小於{1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltecsfield", - translation: "{0}必須小於或等於{1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "nefield", - translation: "{0}不能等於{1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtfield", - translation: "{0}必須大於{1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "gtefield", - translation: "{0}必須大於或等於{1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltfield", - translation: "{0}必須小於{1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "ltefield", - translation: "{0}必須小於或等於{1}", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "alpha", - translation: "{0}只能包含字母", - override: false, - }, - { - tag: "alphanum", - translation: "{0}只能包含字母和數字", - override: false, - }, - { - tag: "numeric", - translation: "{0}必須是一個有效的數值", - override: false, - }, - { - tag: "number", - translation: "{0}必須是一個有效的數字", - override: false, - }, - { - tag: "hexadecimal", - translation: "{0}必須是一個有效的十六進制", - override: false, - }, - { - tag: "hexcolor", - translation: "{0}必須是一個有效的十六進制顏色", - override: false, - }, - { - tag: "rgb", - translation: "{0}必須是一個有效的RGB顏色", - override: false, - }, - { - tag: "rgba", - translation: "{0}必須是一個有效的RGBA顏色", - override: false, - }, - { - tag: "hsl", - translation: "{0}必須是一個有效的HSL顏色", - override: false, - }, - { - tag: "hsla", - translation: "{0}必須是一個有效的HSLA顏色", - override: false, - }, - { - tag: "email", - translation: "{0}必須是一個有效的信箱", - override: false, - }, - { - tag: "url", - translation: "{0}必須是一個有效的URL", - override: false, - }, - { - tag: "uri", - translation: "{0}必須是一個有效的URI", - override: false, - }, - { - tag: "base64", - translation: "{0}必須是一個有效的Base64字元串", - override: false, - }, - { - tag: "contains", - translation: "{0}必須包含文字'{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "containsany", - translation: "{0}必須包含至少一個以下字元'{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludes", - translation: "{0}不能包含文字'{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesall", - translation: "{0}不能包含以下任何字元'{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "excludesrune", - translation: "{0}不能包含'{1}'", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - { - tag: "isbn", - translation: "{0}必須是一個有效的ISBN編號", - override: false, - }, - { - tag: "isbn10", - translation: "{0}必須是一個有效的ISBN-10編號", - override: false, - }, - { - tag: "isbn13", - translation: "{0}必須是一個有效的ISBN-13編號", - override: false, - }, - { - tag: "uuid", - translation: "{0}必須是一個有效的UUID", - override: false, - }, - { - tag: "uuid3", - translation: "{0}必須是一個有效的V3 UUID", - override: false, - }, - { - tag: "uuid4", - translation: "{0}必須是一個有效的V4 UUID", - override: false, - }, - { - tag: "uuid5", - translation: "{0}必須是一個有效的V5 UUID", - override: false, - }, - { - tag: "ascii", - translation: "{0}必須只包含ascii字元", - override: false, - }, - { - tag: "printascii", - translation: "{0}必須只包含可輸出的ascii字元", - override: false, - }, - { - tag: "multibyte", - translation: "{0}必須包含多個字元", - override: false, - }, - { - tag: "datauri", - translation: "{0}必須包含有效的數據URI", - override: false, - }, - { - tag: "latitude", - translation: "{0}必須包含有效的緯度座標", - override: false, - }, - { - tag: "longitude", - translation: "{0}必須包含有效的經度座標", - override: false, - }, - { - tag: "ssn", - translation: "{0}必須是一個有效的社會安全編號(SSN)", - override: false, - }, - { - tag: "ipv4", - translation: "{0}必須是一個有效的IPv4地址", - override: false, - }, - { - tag: "ipv6", - translation: "{0}必須是一個有效的IPv6地址", - override: false, - }, - { - tag: "ip", - translation: "{0}必須是一個有效的IP地址", - override: false, - }, - { - tag: "cidr", - translation: "{0}必須是一個有效的無類別域間路由(CIDR)", - override: false, - }, - { - tag: "cidrv4", - translation: "{0}必須是一个包含IPv4地址的有效無類別域間路由(CIDR)", - override: false, - }, - { - tag: "cidrv6", - translation: "{0}必須是一个包含IPv6地址的有效無類別域間路由(CIDR)", - override: false, - }, - { - tag: "tcp_addr", - translation: "{0}必須是一個有效的TCP地址", - override: false, - }, - { - tag: "tcp4_addr", - translation: "{0}必須是一個有效的IPv4 TCP地址", - override: false, - }, - { - tag: "tcp6_addr", - translation: "{0}必須是一個有效的IPv6 TCP地址", - override: false, - }, - { - tag: "udp_addr", - translation: "{0}必須是一個有效的UDP地址", - override: false, - }, - { - tag: "udp4_addr", - translation: "{0}必須是一個有效的IPv4 UDP地址", - override: false, - }, - { - tag: "udp6_addr", - translation: "{0}必須是一個有效的IPv6 UDP地址", - override: false, - }, - { - tag: "ip_addr", - translation: "{0}必須是一個有效的IP地址", - override: false, - }, - { - tag: "ip4_addr", - translation: "{0}必須是一個有效的IPv4地址", - override: false, - }, - { - tag: "ip6_addr", - translation: "{0}必須是一個有效的IPv6地址", - override: false, - }, - { - tag: "unix_addr", - translation: "{0}必須是一個有效的UNIX地址", - override: false, - }, - { - tag: "mac", - translation: "{0}必須是一個有效的MAC地址", - override: false, - }, - { - tag: "iscolor", - translation: "{0}必須是一個有效的顏色", - override: false, - }, - { - tag: "oneof", - translation: "{0}必須是[{1}]中的一個", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - s, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - return s - }, - }, - { - tag: "datetime", - translation: "{0}與{1}格式不匹配", - override: false, - customTransFunc: func(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field(), fe.Param()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t - }, - }, - } - - for _, t := range translations { - - if t.customTransFunc != nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, t.customTransFunc) - - } else if t.customTransFunc != nil && t.customRegisFunc == nil { - - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), t.customTransFunc) - - } else if t.customTransFunc == nil && t.customRegisFunc != nil { - - err = v.RegisterTranslation(t.tag, trans, t.customRegisFunc, translateFunc) - - } else { - err = v.RegisterTranslation(t.tag, trans, registrationFunc(t.tag, t.translation, t.override), translateFunc) - } - - if err != nil { - return - } - } - - return -} - -func registrationFunc(tag string, translation string, override bool) validator.RegisterTranslationsFunc { - - return func(ut ut.Translator) (err error) { - - if err = ut.Add(tag, translation, override); err != nil { - return - } - - return - - } - -} - -func translateFunc(ut ut.Translator, fe validator.FieldError) string { - - t, err := ut.T(fe.Tag(), fe.Field()) - if err != nil { - log.Printf("警告: 翻譯欄位錯誤: %#v", fe) - return fe.(error).Error() - } - - return t -} diff --git a/go-playground/validator/v10/translations/zh_tw/zh_tw_test.go b/go-playground/validator/v10/translations/zh_tw/zh_tw_test.go deleted file mode 100644 index 301c876..0000000 --- a/go-playground/validator/v10/translations/zh_tw/zh_tw_test.go +++ /dev/null @@ -1,641 +0,0 @@ -package zh_tw - -import ( - "testing" - "time" - - . "git.ningdatech.com/ningda/gin_valid/go-playground/assert/v2" - zhongwen "git.ningdatech.com/ningda/gin_valid/go-playground/locales/zh_Hant_TW" - ut "git.ningdatech.com/ningda/gin_valid/go-playground/universal-translator" - "git.ningdatech.com/ningda/gin_valid/go-playground/validator/v10" -) - -func TestTranslations(t *testing.T) { - - zh := zhongwen.New() - uni := ut.New(zh, zh) - trans, _ := uni.GetTranslator("zh") - - validate := validator.New() - - err := RegisterDefaultTranslations(validate, trans) - Equal(t, err, nil) - - type Inner struct { - EqCSFieldString string - NeCSFieldString string - GtCSFieldString string - GteCSFieldString string - LtCSFieldString string - LteCSFieldString string - } - - type Test struct { - Inner Inner - RequiredString string `validate:"required"` - RequiredNumber int `validate:"required"` - RequiredMultiple []string `validate:"required"` - LenString string `validate:"len=1"` - LenNumber float64 `validate:"len=1113.00"` - LenMultiple []string `validate:"len=7"` - MinString string `validate:"min=1"` - MinNumber float64 `validate:"min=1113.00"` - MinMultiple []string `validate:"min=7"` - MaxString string `validate:"max=3"` - MaxNumber float64 `validate:"max=1113.00"` - MaxMultiple []string `validate:"max=7"` - EqString string `validate:"eq=3"` - EqNumber float64 `validate:"eq=2.33"` - EqMultiple []string `validate:"eq=7"` - NeString string `validate:"ne="` - NeNumber float64 `validate:"ne=0.00"` - NeMultiple []string `validate:"ne=0"` - LtString string `validate:"lt=3"` - LtNumber float64 `validate:"lt=5.56"` - LtMultiple []string `validate:"lt=2"` - LtTime time.Time `validate:"lt"` - LteString string `validate:"lte=3"` - LteNumber float64 `validate:"lte=5.56"` - LteMultiple []string `validate:"lte=2"` - LteTime time.Time `validate:"lte"` - GtString string `validate:"gt=3"` - GtNumber float64 `validate:"gt=5.56"` - GtMultiple []string `validate:"gt=2"` - GtTime time.Time `validate:"gt"` - GteString string `validate:"gte=3"` - GteNumber float64 `validate:"gte=5.56"` - GteMultiple []string `validate:"gte=2"` - GteTime time.Time `validate:"gte"` - EqFieldString string `validate:"eqfield=MaxString"` - EqCSFieldString string `validate:"eqcsfield=Inner.EqCSFieldString"` - NeCSFieldString string `validate:"necsfield=Inner.NeCSFieldString"` - GtCSFieldString string `validate:"gtcsfield=Inner.GtCSFieldString"` - GteCSFieldString string `validate:"gtecsfield=Inner.GteCSFieldString"` - LtCSFieldString string `validate:"ltcsfield=Inner.LtCSFieldString"` - LteCSFieldString string `validate:"ltecsfield=Inner.LteCSFieldString"` - NeFieldString string `validate:"nefield=EqFieldString"` - GtFieldString string `validate:"gtfield=MaxString"` - GteFieldString string `validate:"gtefield=MaxString"` - LtFieldString string `validate:"ltfield=MaxString"` - LteFieldString string `validate:"ltefield=MaxString"` - AlphaString string `validate:"alpha"` - AlphanumString string `validate:"alphanum"` - NumericString string `validate:"numeric"` - NumberString string `validate:"number"` - HexadecimalString string `validate:"hexadecimal"` - HexColorString string `validate:"hexcolor"` - RGBColorString string `validate:"rgb"` - RGBAColorString string `validate:"rgba"` - HSLColorString string `validate:"hsl"` - HSLAColorString string `validate:"hsla"` - Email string `validate:"email"` - URL string `validate:"url"` - URI string `validate:"uri"` - Base64 string `validate:"base64"` - Contains string `validate:"contains=purpose"` - ContainsAny string `validate:"containsany=!@#$"` - Excludes string `validate:"excludes=text"` - ExcludesAll string `validate:"excludesall=!@#$"` - ExcludesRune string `validate:"excludesrune=☻"` - ISBN string `validate:"isbn"` - ISBN10 string `validate:"isbn10"` - ISBN13 string `validate:"isbn13"` - UUID string `validate:"uuid"` - UUID3 string `validate:"uuid3"` - UUID4 string `validate:"uuid4"` - UUID5 string `validate:"uuid5"` - ASCII string `validate:"ascii"` - PrintableASCII string `validate:"printascii"` - MultiByte string `validate:"multibyte"` - DataURI string `validate:"datauri"` - Latitude string `validate:"latitude"` - Longitude string `validate:"longitude"` - SSN string `validate:"ssn"` - IP string `validate:"ip"` - IPv4 string `validate:"ipv4"` - IPv6 string `validate:"ipv6"` - CIDR string `validate:"cidr"` - CIDRv4 string `validate:"cidrv4"` - CIDRv6 string `validate:"cidrv6"` - TCPAddr string `validate:"tcp_addr"` - TCPAddrv4 string `validate:"tcp4_addr"` - TCPAddrv6 string `validate:"tcp6_addr"` - UDPAddr string `validate:"udp_addr"` - UDPAddrv4 string `validate:"udp4_addr"` - UDPAddrv6 string `validate:"udp6_addr"` - IPAddr string `validate:"ip_addr"` - IPAddrv4 string `validate:"ip4_addr"` - IPAddrv6 string `validate:"ip6_addr"` - UinxAddr string `validate:"unix_addr"` // can't fail from within Go's net package currently, but maybe in the future - MAC string `validate:"mac"` - IsColor string `validate:"iscolor"` - StrPtrMinLen *string `validate:"min=10"` - StrPtrMaxLen *string `validate:"max=1"` - StrPtrLen *string `validate:"len=2"` - StrPtrLt *string `validate:"lt=1"` - StrPtrLte *string `validate:"lte=1"` - StrPtrGt *string `validate:"gt=10"` - StrPtrGte *string `validate:"gte=10"` - OneOfString string `validate:"oneof=red green"` - OneOfInt int `validate:"oneof=5 63"` - Datetime string `validate:"datetime=2006-01-02"` - } - - var test Test - - test.Inner.EqCSFieldString = "1234" - test.Inner.GtCSFieldString = "1234" - test.Inner.GteCSFieldString = "1234" - - test.MaxString = "1234" - test.MaxNumber = 2000 - test.MaxMultiple = make([]string, 9) - - test.LtString = "1234" - test.LtNumber = 6 - test.LtMultiple = make([]string, 3) - test.LtTime = time.Now().Add(time.Hour * 24) - - test.LteString = "1234" - test.LteNumber = 6 - test.LteMultiple = make([]string, 3) - test.LteTime = time.Now().Add(time.Hour * 24) - - test.LtFieldString = "12345" - test.LteFieldString = "12345" - - test.LtCSFieldString = "1234" - test.LteCSFieldString = "1234" - - test.AlphaString = "abc3" - test.AlphanumString = "abc3!" - test.NumericString = "12E.00" - test.NumberString = "12E" - - test.Excludes = "this is some test text" - test.ExcludesAll = "This is Great!" - test.ExcludesRune = "Love it ☻" - - test.ASCII = "カタカナ" - test.PrintableASCII = "カタカナ" - - test.MultiByte = "1234feerf" - - s := "toolong" - test.StrPtrMaxLen = &s - test.StrPtrLen = &s - - test.Datetime = "2008-Feb-01" - - err = validate.Struct(test) - NotEqual(t, err, nil) - - errs, ok := err.(validator.ValidationErrors) - Equal(t, ok, true) - - tests := []struct { - ns string - expected string - }{ - { - ns: "Test.IsColor", - expected: "IsColor必須是一個有效的顏色", - }, - { - ns: "Test.MAC", - expected: "MAC必須是一個有效的MAC地址", - }, - { - ns: "Test.IPAddr", - expected: "IPAddr必須是一個有效的IP地址", - }, - { - ns: "Test.IPAddrv4", - expected: "IPAddrv4必須是一個有效的IPv4地址", - }, - { - ns: "Test.IPAddrv6", - expected: "IPAddrv6必須是一個有效的IPv6地址", - }, - { - ns: "Test.UDPAddr", - expected: "UDPAddr必須是一個有效的UDP地址", - }, - { - ns: "Test.UDPAddrv4", - expected: "UDPAddrv4必須是一個有效的IPv4 UDP地址", - }, - { - ns: "Test.UDPAddrv6", - expected: "UDPAddrv6必須是一個有效的IPv6 UDP地址", - }, - { - ns: "Test.TCPAddr", - expected: "TCPAddr必須是一個有效的TCP地址", - }, - { - ns: "Test.TCPAddrv4", - expected: "TCPAddrv4必須是一個有效的IPv4 TCP地址", - }, - { - ns: "Test.TCPAddrv6", - expected: "TCPAddrv6必須是一個有效的IPv6 TCP地址", - }, - { - ns: "Test.CIDR", - expected: "CIDR必須是一個有效的無類別域間路由(CIDR)", - }, - { - ns: "Test.CIDRv4", - expected: "CIDRv4必須是一个包含IPv4地址的有效無類別域間路由(CIDR)", - }, - { - ns: "Test.CIDRv6", - expected: "CIDRv6必須是一个包含IPv6地址的有效無類別域間路由(CIDR)", - }, - { - ns: "Test.SSN", - expected: "SSN必須是一個有效的社會安全編號(SSN)", - }, - { - ns: "Test.IP", - expected: "IP必須是一個有效的IP地址", - }, - { - ns: "Test.IPv4", - expected: "IPv4必須是一個有效的IPv4地址", - }, - { - ns: "Test.IPv6", - expected: "IPv6必須是一個有效的IPv6地址", - }, - { - ns: "Test.DataURI", - expected: "DataURI必須包含有效的數據URI", - }, - { - ns: "Test.Latitude", - expected: "Latitude必須包含有效的緯度座標", - }, - { - ns: "Test.Longitude", - expected: "Longitude必須包含有效的經度座標", - }, - { - ns: "Test.MultiByte", - expected: "MultiByte必須包含多個字元", - }, - { - ns: "Test.ASCII", - expected: "ASCII必須只包含ascii字元", - }, - { - ns: "Test.PrintableASCII", - expected: "PrintableASCII必須只包含可輸出的ascii字元", - }, - { - ns: "Test.UUID", - expected: "UUID必須是一個有效的UUID", - }, - { - ns: "Test.UUID3", - expected: "UUID3必須是一個有效的V3 UUID", - }, - { - ns: "Test.UUID4", - expected: "UUID4必須是一個有效的V4 UUID", - }, - { - ns: "Test.UUID5", - expected: "UUID5必須是一個有效的V5 UUID", - }, - { - ns: "Test.ISBN", - expected: "ISBN必須是一個有效的ISBN編號", - }, - { - ns: "Test.ISBN10", - expected: "ISBN10必須是一個有效的ISBN-10編號", - }, - { - ns: "Test.ISBN13", - expected: "ISBN13必須是一個有效的ISBN-13編號", - }, - { - ns: "Test.Excludes", - expected: "Excludes不能包含文字'text'", - }, - { - ns: "Test.ExcludesAll", - expected: "ExcludesAll不能包含以下任何字元'!@#$'", - }, - { - ns: "Test.ExcludesRune", - expected: "ExcludesRune不能包含'☻'", - }, - { - ns: "Test.ContainsAny", - expected: "ContainsAny必須包含至少一個以下字元'!@#$'", - }, - { - ns: "Test.Contains", - expected: "Contains必須包含文字'purpose'", - }, - { - ns: "Test.Base64", - expected: "Base64必須是一個有效的Base64字元串", - }, - { - ns: "Test.Email", - expected: "Email必須是一個有效的信箱", - }, - { - ns: "Test.URL", - expected: "URL必須是一個有效的URL", - }, - { - ns: "Test.URI", - expected: "URI必須是一個有效的URI", - }, - { - ns: "Test.RGBColorString", - expected: "RGBColorString必須是一個有效的RGB顏色", - }, - { - ns: "Test.RGBAColorString", - expected: "RGBAColorString必須是一個有效的RGBA顏色", - }, - { - ns: "Test.HSLColorString", - expected: "HSLColorString必須是一個有效的HSL顏色", - }, - { - ns: "Test.HSLAColorString", - expected: "HSLAColorString必須是一個有效的HSLA顏色", - }, - { - ns: "Test.HexadecimalString", - expected: "HexadecimalString必須是一個有效的十六進制", - }, - { - ns: "Test.HexColorString", - expected: "HexColorString必須是一個有效的十六進制顏色", - }, - { - ns: "Test.NumberString", - expected: "NumberString必須是一個有效的數字", - }, - { - ns: "Test.NumericString", - expected: "NumericString必須是一個有效的數值", - }, - { - ns: "Test.AlphanumString", - expected: "AlphanumString只能包含字母和數字", - }, - { - ns: "Test.AlphaString", - expected: "AlphaString只能包含字母", - }, - { - ns: "Test.LtFieldString", - expected: "LtFieldString必須小於MaxString", - }, - { - ns: "Test.LteFieldString", - expected: "LteFieldString必須小於或等於MaxString", - }, - { - ns: "Test.GtFieldString", - expected: "GtFieldString必須大於MaxString", - }, - { - ns: "Test.GteFieldString", - expected: "GteFieldString必須大於或等於MaxString", - }, - { - ns: "Test.NeFieldString", - expected: "NeFieldString不能等於EqFieldString", - }, - { - ns: "Test.LtCSFieldString", - expected: "LtCSFieldString必須小於Inner.LtCSFieldString", - }, - { - ns: "Test.LteCSFieldString", - expected: "LteCSFieldString必須小於或等於Inner.LteCSFieldString", - }, - { - ns: "Test.GtCSFieldString", - expected: "GtCSFieldString必須大於Inner.GtCSFieldString", - }, - { - ns: "Test.GteCSFieldString", - expected: "GteCSFieldString必須大於或等於Inner.GteCSFieldString", - }, - { - ns: "Test.NeCSFieldString", - expected: "NeCSFieldString不能等於Inner.NeCSFieldString", - }, - { - ns: "Test.EqCSFieldString", - expected: "EqCSFieldString必須等於Inner.EqCSFieldString", - }, - { - ns: "Test.EqFieldString", - expected: "EqFieldString必須等於MaxString", - }, - { - ns: "Test.GteString", - expected: "GteString長度必須至少為3個字元", - }, - { - ns: "Test.GteNumber", - expected: "GteNumber必須大於或等於5.56", - }, - { - ns: "Test.GteMultiple", - expected: "GteMultiple必須至少包含2項", - }, - { - ns: "Test.GteTime", - expected: "GteTime必須大於或等於目前日期和時間", - }, - { - ns: "Test.GtString", - expected: "GtString長度必須大於3個字元", - }, - { - ns: "Test.GtNumber", - expected: "GtNumber必須大於5.56", - }, - { - ns: "Test.GtMultiple", - expected: "GtMultiple必須大於2項", - }, - { - ns: "Test.GtTime", - expected: "GtTime必須大於目前日期和時間", - }, - { - ns: "Test.LteString", - expected: "LteString長度不能超過3個字元", - }, - { - ns: "Test.LteNumber", - expected: "LteNumber必須小於或等於5.56", - }, - { - ns: "Test.LteMultiple", - expected: "LteMultiple最多只能包含2項", - }, - { - ns: "Test.LteTime", - expected: "LteTime必須小於或等於目前日期和時間", - }, - { - ns: "Test.LtString", - expected: "LtString長度必須小於3個字元", - }, - { - ns: "Test.LtNumber", - expected: "LtNumber必須小於5.56", - }, - { - ns: "Test.LtMultiple", - expected: "LtMultiple必須包含少於2項", - }, - { - ns: "Test.LtTime", - expected: "LtTime必須小於目前日期和時間", - }, - { - ns: "Test.NeString", - expected: "NeString不能等於", - }, - { - ns: "Test.NeNumber", - expected: "NeNumber不能等於0.00", - }, - { - ns: "Test.NeMultiple", - expected: "NeMultiple不能等於0", - }, - { - ns: "Test.EqString", - expected: "EqString不等於3", - }, - { - ns: "Test.EqNumber", - expected: "EqNumber不等於2.33", - }, - { - ns: "Test.EqMultiple", - expected: "EqMultiple不等於7", - }, - { - ns: "Test.MaxString", - expected: "MaxString長度不能超過3個字元", - }, - { - ns: "Test.MaxNumber", - expected: "MaxNumber必須小於或等於1,113.00", - }, - { - ns: "Test.MaxMultiple", - expected: "MaxMultiple最多只能包含7項", - }, - { - ns: "Test.MinString", - expected: "MinString長度必須至少為1個字元", - }, - { - ns: "Test.MinNumber", - expected: "MinNumber最小只能為1,113.00", - }, - { - ns: "Test.MinMultiple", - expected: "MinMultiple必須至少包含7項", - }, - { - ns: "Test.LenString", - expected: "LenString長度必須為1個字元", - }, - { - ns: "Test.LenNumber", - expected: "LenNumber必須等於1,113.00", - }, - { - ns: "Test.LenMultiple", - expected: "LenMultiple必須包含7項", - }, - { - ns: "Test.RequiredString", - expected: "RequiredString為必填欄位", - }, - { - ns: "Test.RequiredNumber", - expected: "RequiredNumber為必填欄位", - }, - { - ns: "Test.RequiredMultiple", - expected: "RequiredMultiple為必填欄位", - }, - { - ns: "Test.StrPtrMinLen", - expected: "StrPtrMinLen長度必須至少為10個字元", - }, - { - ns: "Test.StrPtrMaxLen", - expected: "StrPtrMaxLen長度不能超過1個字元", - }, - { - ns: "Test.StrPtrLen", - expected: "StrPtrLen長度必須為2個字元", - }, - { - ns: "Test.StrPtrLt", - expected: "StrPtrLt長度必須小於1個字元", - }, - { - ns: "Test.StrPtrLte", - expected: "StrPtrLte長度不能超過1個字元", - }, - { - ns: "Test.StrPtrGt", - expected: "StrPtrGt長度必須大於10個字元", - }, - { - ns: "Test.StrPtrGte", - expected: "StrPtrGte長度必須至少為10個字元", - }, - { - ns: "Test.OneOfString", - expected: "OneOfString必須是[red green]中的一個", - }, - { - ns: "Test.OneOfInt", - expected: "OneOfInt必須是[5 63]中的一個", - }, - { - ns: "Test.Datetime", - expected: "Datetime與2006-01-02格式不匹配", - }, - } - - for _, tt := range tests { - - var fe validator.FieldError - - for _, e := range errs { - if tt.ns == e.Namespace() { - fe = e - break - } - } - - NotEqual(t, fe, nil) - Equal(t, tt.expected, fe.Translate(trans)) - } - -}