:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving

Overview

Package validator

Join the chat at https://gitter.im/go-playground/validator Project status Build Status Coverage Status Go Report Card GoDoc License

Package validator implements value validations for structs and individual fields based on tags.

It has the following unique features:

  • Cross Field and Cross Struct validations by using validation tags or custom validators.
  • Slice, Array and Map diving, which allows any or all levels of a multidimensional field to be validated.
  • Ability to dive into both map keys and values for validation
  • Handles type interface by determining it's underlying type prior to validation.
  • Handles custom field types such as sql driver Valuer see Valuer
  • Alias validation tags, which allows for mapping of several validations to a single tag for easier defining of validations on structs
  • Extraction of custom defined Field Name e.g. can specify to extract the JSON name while validating and have it available in the resulting FieldError
  • Customizable i18n aware error messages.
  • Default validator for the gin web framework; upgrading from v8 to v9 in gin see here

Installation

Use go get.

go get github.com/go-playground/validator/v10

Then import the validator package into your own code.

import "github.com/go-playground/validator/v10"

Error Return Value

Validation functions return type error

They return type error to avoid the issue discussed in the following, where err is always != nil:

Validator only InvalidValidationError for bad validation input, nil or ValidationErrors as type error; so, in your code all you need to do is check if the error returned is not nil, and if it's not check if error is InvalidValidationError ( if necessary, most of the time it isn't ) type cast it to type ValidationErrors like so:

err := validate.Struct(mystruct)
validationErrors := err.(validator.ValidationErrors)

Usage and documentation

Please see https://godoc.org/github.com/go-playground/validator for detailed usage docs.

Examples:

Baked-in Validations

Fields:

Tag Description
eqcsfield Field Equals Another Field (relative)
eqfield Field Equals Another Field
fieldcontains NOT DOCUMENTED IN doc.go
fieldexcludes NOT DOCUMENTED IN doc.go
gtcsfield Field Greater Than Another Relative Field
gtecsfield Field Greater Than or Equal To Another Relative Field
gtefield Field Greater Than or Equal To Another Field
gtfield Field Greater Than Another Field
ltcsfield Less Than Another Relative Field
ltecsfield Less Than or Equal To Another Relative Field
ltefield Less Than or Equal To Another Field
ltfield Less Than Another Field
necsfield Field Does Not Equal Another Field (relative)
nefield Field Does Not Equal Another Field

Network:

Tag Description
cidr Classless Inter-Domain Routing CIDR
cidrv4 Classless Inter-Domain Routing CIDRv4
cidrv6 Classless Inter-Domain Routing CIDRv6
datauri Data URL
fqdn Full Qualified Domain Name (FQDN)
hostname Hostname RFC 952
hostname_port HostPort
hostname_rfc1123 Hostname RFC 1123
ip Internet Protocol Address IP
ip4_addr Internet Protocol Address IPv4
ip6_addr Internet Protocol Address IPv6
ip_addr Internet Protocol Address IP
ipv4 Internet Protocol Address IPv4
ipv6 Internet Protocol Address IPv6
mac Media Access Control Address MAC
tcp4_addr Transmission Control Protocol Address TCPv4
tcp6_addr Transmission Control Protocol Address TCPv6
tcp_addr Transmission Control Protocol Address TCP
udp4_addr User Datagram Protocol Address UDPv4
udp6_addr User Datagram Protocol Address UDPv6
udp_addr User Datagram Protocol Address UDP
unix_addr Unix domain socket end point Address
uri URI String
url URL String
url_encoded URL Encoded
urn_rfc2141 Urn RFC 2141 String

Strings:

Tag Description
alpha Alpha Only
alphanum Alphanumeric
alphanumunicode Alphanumeric Unicode
alphaunicode Alpha Unicode
ascii ASCII
contains Contains
containsany Contains Any
containsrune Contains Rune
endswith Ends With
lowercase Lowercase
multibyte Multi-Byte Characters
number NOT DOCUMENTED IN doc.go
numeric Numeric
printascii Printable ASCII
startswith Starts With
uppercase Uppercase

Format:

Tag Description
base64 Base64 String
base64url Base64URL String
btc_addr Bitcoin Address
btc_addr_bech32 Bitcoin Bech32 Address (segwit)
datetime Datetime
e164 e164 formatted phone number
email E-mail String
eth_addr Ethereum Address
hexadecimal Hexadecimal String
hexcolor Hexcolor String
hsl HSL String
hsla HSLA String
html HTML Tags
html_encoded HTML Encoded
isbn International Standard Book Number
isbn10 International Standard Book Number 10
isbn13 International Standard Book Number 13
json JSON
latitude Latitude
longitude Longitude
rgb RGB String
rgba RGBA String
ssn Social Security Number SSN
uuid Universally Unique Identifier UUID
uuid3 Universally Unique Identifier UUID v3
uuid3_rfc4122 Universally Unique Identifier UUID v3 RFC4122
uuid4 Universally Unique Identifier UUID v4
uuid4_rfc4122 Universally Unique Identifier UUID v4 RFC4122
uuid5 Universally Unique Identifier UUID v5
uuid5_rfc4122 Universally Unique Identifier UUID v5 RFC4122
uuid_rfc4122 Universally Unique Identifier UUID RFC4122

Comparisons:

Tag Description
eq Equals
gt Greater than
gte Greater than or equal
lt Less Than
lte Less Than or Equal
ne Not Equal

Other:

Tag Description
dir Directory
endswith Ends With
excludes Excludes
excludesall Excludes All
excludesrune Excludes Rune
file File path
isdefault Is Default
len Length
max Maximum
min Minimum
oneof One Of
required Required
required_if Required If
required_unless Required Unless
required_with Required With
required_with_all Required With All
required_without Required Without
required_without_all Required Without All
excluded_with Excluded With
excluded_with_all Excluded With All
excluded_without Excluded Without
excluded_without_all Excluded Without All
unique Unique

Benchmarks

Run on MacBook Pro (15-inch, 2017) go version go1.10.2 darwin/amd64
goos: darwin
goarch: amd64
pkg: github.com/go-playground/validator
BenchmarkFieldSuccess-8                                         20000000                83.6 ns/op             0 B/op          0 allocs/op
BenchmarkFieldSuccessParallel-8                                 50000000                26.8 ns/op             0 B/op          0 allocs/op
BenchmarkFieldFailure-8                                          5000000               291 ns/op             208 B/op          4 allocs/op
BenchmarkFieldFailureParallel-8                                 20000000               107 ns/op             208 B/op          4 allocs/op
BenchmarkFieldArrayDiveSuccess-8                                 2000000               623 ns/op             201 B/op         11 allocs/op
BenchmarkFieldArrayDiveSuccessParallel-8                        10000000               237 ns/op             201 B/op         11 allocs/op
BenchmarkFieldArrayDiveFailure-8                                 2000000               859 ns/op             412 B/op         16 allocs/op
BenchmarkFieldArrayDiveFailureParallel-8                         5000000               335 ns/op             413 B/op         16 allocs/op
BenchmarkFieldMapDiveSuccess-8                                   1000000              1292 ns/op             432 B/op         18 allocs/op
BenchmarkFieldMapDiveSuccessParallel-8                           3000000               467 ns/op             432 B/op         18 allocs/op
BenchmarkFieldMapDiveFailure-8                                   1000000              1082 ns/op             512 B/op         16 allocs/op
BenchmarkFieldMapDiveFailureParallel-8                           5000000               425 ns/op             512 B/op         16 allocs/op
BenchmarkFieldMapDiveWithKeysSuccess-8                           1000000              1539 ns/op             480 B/op         21 allocs/op
BenchmarkFieldMapDiveWithKeysSuccessParallel-8                   3000000               613 ns/op             480 B/op         21 allocs/op
BenchmarkFieldMapDiveWithKeysFailure-8                           1000000              1413 ns/op             721 B/op         21 allocs/op
BenchmarkFieldMapDiveWithKeysFailureParallel-8                   3000000               575 ns/op             721 B/op         21 allocs/op
BenchmarkFieldCustomTypeSuccess-8                               10000000               216 ns/op              32 B/op          2 allocs/op
BenchmarkFieldCustomTypeSuccessParallel-8                       20000000                82.2 ns/op            32 B/op          2 allocs/op
BenchmarkFieldCustomTypeFailure-8                                5000000               274 ns/op             208 B/op          4 allocs/op
BenchmarkFieldCustomTypeFailureParallel-8                       20000000               116 ns/op             208 B/op          4 allocs/op
BenchmarkFieldOrTagSuccess-8                                     2000000               740 ns/op              16 B/op          1 allocs/op
BenchmarkFieldOrTagSuccessParallel-8                             3000000               474 ns/op              16 B/op          1 allocs/op
BenchmarkFieldOrTagFailure-8                                     3000000               471 ns/op             224 B/op          5 allocs/op
BenchmarkFieldOrTagFailureParallel-8                             3000000               414 ns/op             224 B/op          5 allocs/op
BenchmarkStructLevelValidationSuccess-8                         10000000               213 ns/op              32 B/op          2 allocs/op
BenchmarkStructLevelValidationSuccessParallel-8                 20000000                91.8 ns/op            32 B/op          2 allocs/op
BenchmarkStructLevelValidationFailure-8                          3000000               473 ns/op             304 B/op          8 allocs/op
BenchmarkStructLevelValidationFailureParallel-8                 10000000               234 ns/op             304 B/op          8 allocs/op
BenchmarkStructSimpleCustomTypeSuccess-8                         5000000               385 ns/op              32 B/op          2 allocs/op
BenchmarkStructSimpleCustomTypeSuccessParallel-8                10000000               161 ns/op              32 B/op          2 allocs/op
BenchmarkStructSimpleCustomTypeFailure-8                         2000000               640 ns/op             424 B/op          9 allocs/op
BenchmarkStructSimpleCustomTypeFailureParallel-8                 5000000               318 ns/op             440 B/op         10 allocs/op
BenchmarkStructFilteredSuccess-8                                 2000000               597 ns/op             288 B/op          9 allocs/op
BenchmarkStructFilteredSuccessParallel-8                        10000000               266 ns/op             288 B/op          9 allocs/op
BenchmarkStructFilteredFailure-8                                 3000000               454 ns/op             256 B/op          7 allocs/op
BenchmarkStructFilteredFailureParallel-8                        10000000               214 ns/op             256 B/op          7 allocs/op
BenchmarkStructPartialSuccess-8                                  3000000               502 ns/op             256 B/op          6 allocs/op
BenchmarkStructPartialSuccessParallel-8                         10000000               225 ns/op             256 B/op          6 allocs/op
BenchmarkStructPartialFailure-8                                  2000000               702 ns/op             480 B/op         11 allocs/op
BenchmarkStructPartialFailureParallel-8                          5000000               329 ns/op             480 B/op         11 allocs/op
BenchmarkStructExceptSuccess-8                                   2000000               793 ns/op             496 B/op         12 allocs/op
BenchmarkStructExceptSuccessParallel-8                          10000000               193 ns/op             240 B/op          5 allocs/op
BenchmarkStructExceptFailure-8                                   2000000               639 ns/op             464 B/op         10 allocs/op
BenchmarkStructExceptFailureParallel-8                           5000000               300 ns/op             464 B/op         10 allocs/op
BenchmarkStructSimpleCrossFieldSuccess-8                         3000000               417 ns/op              72 B/op          3 allocs/op
BenchmarkStructSimpleCrossFieldSuccessParallel-8                10000000               163 ns/op              72 B/op          3 allocs/op
BenchmarkStructSimpleCrossFieldFailure-8                         2000000               645 ns/op             304 B/op          8 allocs/op
BenchmarkStructSimpleCrossFieldFailureParallel-8                 5000000               285 ns/op             304 B/op          8 allocs/op
BenchmarkStructSimpleCrossStructCrossFieldSuccess-8              3000000               588 ns/op              80 B/op          4 allocs/op
BenchmarkStructSimpleCrossStructCrossFieldSuccessParallel-8     10000000               221 ns/op              80 B/op          4 allocs/op
BenchmarkStructSimpleCrossStructCrossFieldFailure-8              2000000               868 ns/op             320 B/op          9 allocs/op
BenchmarkStructSimpleCrossStructCrossFieldFailureParallel-8      5000000               337 ns/op             320 B/op          9 allocs/op
BenchmarkStructSimpleSuccess-8                                   5000000               260 ns/op               0 B/op          0 allocs/op
BenchmarkStructSimpleSuccessParallel-8                          20000000                90.6 ns/op             0 B/op          0 allocs/op
BenchmarkStructSimpleFailure-8                                   2000000               619 ns/op             424 B/op          9 allocs/op
BenchmarkStructSimpleFailureParallel-8                           5000000               296 ns/op             424 B/op          9 allocs/op
BenchmarkStructComplexSuccess-8                                  1000000              1454 ns/op             128 B/op          8 allocs/op
BenchmarkStructComplexSuccessParallel-8                          3000000               579 ns/op             128 B/op          8 allocs/op
BenchmarkStructComplexFailure-8                                   300000              4140 ns/op            3041 B/op         53 allocs/op
BenchmarkStructComplexFailureParallel-8                          1000000              2127 ns/op            3041 B/op         53 allocs/op
BenchmarkOneof-8                                                10000000               140 ns/op               0 B/op          0 allocs/op
BenchmarkOneofParallel-8                                        20000000                70.1 ns/op             0 B/op          0 allocs/op

Complementary Software

Here is a list of software that complements using this library either pre or post validation.

  • form - Decodes url.Values into Go value(s) and Encodes Go value(s) into url.Values. Dual Array and Full map support.
  • mold - A general library to help modify or set data within data structures and other objects

How to Contribute

Make a pull request...

License

Distributed under MIT License, please see license file within the code for more details.

Issues
  • How to validate `bool`

    How to validate `bool`

    type Thing struct {
      Truthiness bool `json:"truthiness" validate:"required"`
    }
    

    Using gin-gonic/gin with this, when it marshals JSON into a struct, this passes:

    { "truthiness": true }
    

    But this fails, b/c it is the golang zero-value for bool

    { "truthiness": false }
    

    I just want to validate that the property exists -- if it exists, I know it will have a value of true or false.

    Nothing obvious popped out at me from: https://godoc.org/gopkg.in/bluesuncorp/validator.v5#pkg-variables

    question 
    opened by davisford 24
  • cannot find package

    cannot find package "github.com/go-playground/validator/v10" in any of

    Package version eg. v8, v9:

    v10

    Issue, Question or Enhancement:

    go get github.com/go-playground/validator/v10
    

    give following error

    package github.com/go-playground/validator/v10: cannot find package "github.com/go-playground/validator/v10" in any of:
            /usr/local/go/src/github.com/go-playground/validator/v10 (from $GOROOT)
            /go/src/github.com/go-playground/validator/v10 (from $GOPATH)
    
    

    Code sample, to showcase or reproduce:

    using golang docker latest

    $ docker run -it --rm golang sh
    $ go get github.com/go-playground/validator/v10
    package github.com/go-playground/validator/v10: cannot find package "github.com/go-playground/validator/v10" in any of:
            /usr/local/go/src/github.com/go-playground/validator/v10 (from $GOROOT)
            /go/src/github.com/go-playground/validator/v10 (from $GOPATH)
    
    opened by faisalburhanudin 20
  • Add validation functions for tcp/udp/ip/unix addresses

    Add validation functions for tcp/udp/ip/unix addresses

    What do you think of those fileds? If you think it's good idea I can create some docs + tests.

    Why I think is good? I constatly need to parse some bind addreses for other services (http, etc....) and would be nice to validate those adresses, not it time when service will be starded.

    in-progress review 
    opened by krhubert 18
  • Dive into and validate map keys?

    Dive into and validate map keys?

    Package version eg. v8, v9:

    v9

    Issue, Question or Enhancement:

    Question

    Code sample, to showcase or reproduce:

    
    package main
    
    import (
        "fmt"
        "gopkg.in/go-playground/validator.v9"
    )
    
    type LangCode string
    type Label map[LangCode]string
    
    type TestMapStructPtr struct {
        Label Label `validate:"lang_code,dive,required"`
    }
    
    var validate *validator.Validate
    
    func main() {
    
        validate = validator.New()
        validate.RegisterValidation("lang_code", ValidLangCode)
    
        label := Label {
            "en":"Good morning!",
            "pt":"Bom dia!",
            "es":"¡Buenos días!",
            "is":"Góðan daginn",
        }
    
        err := validate.Struct(TestMapStructPtr{label})
        // hoping to catch that "is" key is not valid
        if err != nil {
            fmt.Printf("label not valid! %s\n", err)
        }
    }
    
    func ValidLangCode(fl validator.FieldLevel) bool {
        validLangCodes := map[string]bool{
            "en":true,
            "es":true,
            "pt":true,
        }
        fmt.Printf("Validating %s\n", fl.Field())
        return validLangCodes[fl.Field().String()]
    }
    

    Hello, I am very new to the validator so I apologize if I've misinterpreted the use of dive and maps! I'm also aware the above can be accomplished with Label as a struct, but I'm wondering if validator supports validating map keys using custom validations.

    Is there a way to validate the keys of a map?

    The above code example, I was expecting the validation rule "lang_code,dive,required" would validate each map key against the lang_code validation, and the value as required.

    However, running the above code I see that ValidLangCode is receiving the entire map, not each key. Is there any way to dive into the keys? Trying other combinations of dive, lang_code, and required didn't seem to work.

    thanks!

    new question 
    opened by adrian-sgn 16
  • Validate nested structs

    Validate nested structs

    Fixes #367 .

    Make sure that you've checked the boxes below before you submit PR:

    • [x] Tests exist or have been written that cover this particular change.

    Change Details: This change allows using (any: custom or backed in) validations on nested structs.

    @go-playground/admins

    opened by zenovich 14
  • required_without does not work with pointers

    required_without does not work with pointers

    Package version eg. v8, v9:

    v9

    Issue, Question or Enhancement:

    required_without does not work with pointers

    Code sample, to showcase or reproduce:

    Playground: https://play.golang.org/p/5hpXOfDJU4V

    package main
    
    import (
    	"fmt"
    	"gopkg.in/go-playground/validator.v9"
    )
    
    type a struct {
    	Field1 *string `validate:"required_without=Field2"`
    	Field2 *int    `validate:"required_without=Field1"`
    }
    
    func main() {
    	validate := validator.New()
    
    	testStr := new(string)
    	*testStr = "abcd"
    
    	testInt := new(int)
    	*testInt = 42
    
    	if err := validate.Struct(a{Field1: testStr}); err != nil {
    		fmt.Println(err)
    	} else {
    		fmt.Println("Test A OK")
    	}
    
    	if err := validate.Struct(a{Field2: testInt}); err != nil {
    		fmt.Println(err)
    	} else {
    		fmt.Println("Test B OK")
    	}
    
    	if err := validate.Struct(a{Field1: testStr, Field2: testInt}); err != nil {
    		fmt.Println(err)
    	} else {
    		fmt.Println("Test C OK")
    	}
    }
    
    help wanted 
    opened by tbe 14
  • Add NotBlank validation function.

    Add NotBlank validation function.

    Change Details:

    • There are cases when a value needs to not be empty (like a string containing only spaces, slice not nil but with no elements) and I added a new tag to easily overcome this need.
    type TestString struct {
    	NotBlank  string `validate:"notblank"`
    }
    

    @go-playground/admins

    opened by andreiavrammsd 13
  • Is it possible to have a required cross-field validation?

    Is it possible to have a required cross-field validation?

    Hi @joeybloggs, I'm using your package to perform some validation on data that I'm receiving via API.

    I'd like to know if there is the possibility (and I missed it) to perform a required cross-field validation.

    What I want to achieve is having a validation that returns OK if one of two fields is present on my struct...something like this:

    type Field struct {
       Value1 string `validate:"at_least_one_required"`
       Value2 string `validate:"at_least_one_required"`
       ...
    }
    

    and the validator returns an error if no one of the two fields is not set up.

    Is that possible?

    Thanks, Marco

    question 
    opened by MarcoVigna17 13
  • validate.Struct() always return error

    validate.Struct() always return error

    hi, i am new in golang, maybe that problem about me.

    when i use validator.Struct() in a function that return named error, the err var always not nil

    func ValidateStruct(v interface{}) (err error) {
        err = validate.Struct(v)
        return
    }
    

    but when i use it like this, it works

    func ValidateStruct(v interface{}) (err error) {
        errs := validate.Struct(v)
        if errs != nil {
            err = errs
            return
        }
        return nil
    }
    

    so what the problem ?

    question investigation 
    opened by alioygur 13
  • Let validators see current fields paths

    Let validators see current fields paths

    Fixes Or Enhances # .

    Make sure that you've checked the boxes below before you submit PR:

    • [x] Tests exist or have been written that cover this particular change.

    Change Details:

    Currently there is no way for validators to know which fields they are checking. So validators depending not only on the value, but on the field itself (e.g. checking that the field is listed in some external source) cannot work.

    This PR adds new methods Path() & StructPath() into the FieldLevel interface allowing validators to get a path (based on FieldName-s) or a struct path (based on StructFieldName-s) of the current field respectively.

    @go-playground/admins

    opened by zenovich 12
  • Add Valuer interface support

    Add Valuer interface support

    The Valuer interface in the sql/driver package seems like one of the primary ways for SQL drivers and ORMs to interact with databases, particularly when NULL values are a possibility.

    It would be great if the validator could apply validations directly to Value() values in the case of a type that supports the interface. This would make validations on values of type sql.NullXXX much more straightforward.

    BTW - Thanks for making this package. It's been very handy.

    new review 
    opened by johnniedoe 12
  • Extracting values associated with a tag when validating a struct

    Extracting values associated with a tag when validating a struct

    • [-] I have looked at the documentation here first?
    • [-] I have looked at the examples provided that may showcase my question here?

    v9

    Issue, Question or Enhancement:

    I am using validator with baked in tags and need the tag values to override an existing function. eg for tag min=1, I want to extract 1. Can someone provide some thoughts on this? I tried checking multiple functions provided by FieldLevel interface but none of them provide me the value I am looking for.

    Code sample, to showcase or reproduce:

    
    type Name struct {
    	FamilyName string `json:"familyName,omitempty" validate:"required,min=1,max=255"`
    	GivenName  string `json:"givenName,omitempty" validate:"required,min=1,max=255"`
    }
    
    // inside validate.go we register custom translator
    
    {
    	tag: "min",
    	customRegisFunc: func(ut ut.Translator) error {
    		return ut.Add("min", "'{0}' does not satisfy minimum length requirements. ", true)
    	},
    	customTransFunc: func(ut ut.Translator, fe validator.FieldError) string {
    		t, _ := ut.T("min", fe.Field())
    		return t
    	},
    	customValidFunc: func(fl validator.FieldLevel) bool {
    		if input, ok := fl.Field().Interface().(string); ok {
    	 		param := fl.Param()
    	 		size := fl.Field()
    	 		name := fl.FieldName()
    	 		tag := fl.GetTag()
    	 		value, kind, _ := fl.ExtractType(fl.Field())
    	 		if len(strings.TrimSpace(input)) < {value from tag i.e min=1 hence 1} {
    	 			return false
    	 		}
     	         }
    		return true
            },
    }
    
    
    opened by akib-maredia 0
  • How to validator a   struct  that overiding field in embedding struct

    How to validator a struct that overiding field in embedding struct

    Package version v10:

    Question

    I want to validate the B struct, when T2 is not empty can pass the vaildate . the 'T1' in A is ignored.

    type A struct {
    	T1 string `validate:"required"`
    	T2 string `validate:"required"`
    }
    type B struct {
    	T1 string // is not required
    	A
    }
    // In this case, json works good. sometimes I need to change the A sturct.
    

    I try the 'structonly',but does't work. I need your guidance.

    I'm sorry my English is poor At last,Thank you for your work.

    opened by liuv3v6 0
  • Enhancement: Allow enforcing uniqueness for combination of slice of struct fields

    Enhancement: Allow enforcing uniqueness for combination of slice of struct fields

    • [x] I have looked at the documentation here first?
    • [x] I have looked at the examples provided that may showcase my question here?

    Package version eg. v9, v10:

    v10

    Issue, Question or Enhancement:

    Enchancement

    Allow unique=field1,field2 for slice of structs, where the combination of the two fields must be unique, but there can be duplicates across the fields individually

    Code sample, to showcase or reproduce:

    type ExampleInner struct {
    	s1 string
    	s2 string
    }
    
    type Example struct {
    	e []ExampleInner `validate:"unique=s1,s2"`
    }
    
    example1 := Example{e: []ExampleInner{
      {"s1", "s2"},
      {"s1", "s3"},
    }} //valid
    example2 := Example{e: []ExampleInner{
      {"a", "b"},
      {"c", "b"},
    }} //valid
    example3 := Example{e: []ExampleInner{
      {"a", "b"},
      {"a", "b"},
    }} //invalid
    
    opened by Wasorma 0
  • pt_BR translation improvements

    pt_BR translation improvements

    Fixes Or Enhances

    Make sure that you've checked the boxes below before you submit PR:

    • [x] Tests exist or have been written that cover this particular change.

    @go-playground/validator-maintainers

    opened by cyruzin 1
  • Uppercase/lowercase/numberic etc, for

    Uppercase/lowercase/numberic etc, for "at least 1" char

    • [X] I have looked at the documentation here first?
    • [X] I have looked at the examples provided that may showcase my question here?

    Package version eg. v9, v10:

    v10

    Issue, Question or Enhancement:

    For certain validation, such as "uppercase", "numeric", etc, Is there a way to specify that a given string only needs to contain ONE of these types, instead of ALL.

    Code sample, to showcase or reproduce:

    // Of course the below doesn't work. Just an example of what I was looking for.
    // I can of course write custom validator funcs, just wondering if this if possible without custom funcs.
    
    type NewUser struct {
    	Username string `json:"username" binding:"required,alphanum"`
    	Password string `json:"password" binding:"required,gt=12,uppercase=oneof,lowercase=oneof,numeric=oneof"`
    	Email    string `json:"email" binding:"required,email"`
    }
    
    // Or maybe:
    type NewUser struct {
    	Username string `json:"username" binding:"required,alphanum"`
    	Password string `json:"password" binding:"required,gt=12,oneof=uppercase&lowercase&numeric"`
    	Email    string `json:"email" binding:"required,email"`
    }
    

    In this case, the string "Password1234" would be valid, but "PASSWORD1234" would not.

    opened by adamwoolhether 0
  • Errors thrown by `golangci-lint` for validator package

    Errors thrown by `golangci-lint` for validator package

    • [X] I have looked at the documentation here first?
    • [X] I have looked at the examples provided that may showcase my question here?

    Package version eg. v9, v10:

    v9.31.0

    Issue, Question or Enhancement:

    When using the golangci-lint watcher provided by GoLand: image Every time a file is saved, I get errors from the validator package:

    mypath/my_file.go:245:14: undeclared name: `validator` (typecheck)
    	validate := validator.New()
    

    and also:

    mypath/my_file.go:16:2: "gopkg.in/go-playground/validator.v9" imported but not used (typecheck)
    	"gopkg.in/go-playground/validator.v9"
    

    For each one of the files I am using the package: image

    I can see it runs the following command: golangci-lint run --disable=typecheck

    Code sample, to showcase or reproduce:

    https://goplay.tools/snippet/b--sydpv40H

    package main
    
    import (
    	"github.com/gofrs/uuid"
    	"gopkg.in/go-playground/validator.v9"
    )
    
    type MyRequest struct {
    	UserID uuid.UUID `json:"user_id" validate:"required"`
    }
    
    func main() {
    	request := &MyRequest{UserID: uuid.Must(uuid.NewV4())}
    
    	validate := validator.New()
    	err := validate.Struct(request)
    	if err != nil {
    		panic(err)
    	}
    }
    

    Save file, then run:

    golangci-lint run --disable=typecheck yourfile.go
    
    opened by echarrod 0
Releases(v10.11.0)
  • v10.11.0(May 1, 2022)

    What's new?

    • Add ability to validate structs using map rules. https://github.com/go-playground/validator/pull/934
    • A number of hash validations. https://github.com/go-playground/validator/pull/875
    • Italian translations. https://github.com/go-playground/validator/pull/694/ https://github.com/go-playground/validator/pull/914
    • Vietnamese translations. https://github.com/go-playground/validator/pull/820/
    • Arabic translations. https://github.com/go-playground/validator/pull/825
    • Added missing Boolean translation. https://github.com/go-playground/validator/pull/930
    • Add missing required translation. https://github.com/go-playground/validator/pull/884
    • Add missing zh translations. https://github.com/go-playground/validator/pull/856
    • Added exclude_if and excluded_unless tags. https://github.com/go-playground/validator/pull/847
    • Added Credit Card validation. https://github.com/go-playground/validator/pull/924

    What was fixed?

    • Fix support for aliased time.Time types. https://github.com/go-playground/validator/pull/890
    • Fix multiple group of OR operators. https://github.com/go-playground/validator/pull/911/
    • Remove underscore from RFC-1123 based regex. https://github.com/go-playground/validator/pull/912
    • ja typos. https://github.com/go-playground/validator/pull/898
    • Documentation typos. https://github.com/go-playground/validator/pull/891

    What was enhanced?

    • ValidationCtx now supports nested slice maps. https://github.com/go-playground/validator/pull/917/
    • RegisterTagNameFunc documentation. RegisterTagNameFunc
    Source code(tar.gz)
    Source code(zip)
  • v10.10.1(Mar 8, 2022)

  • v10.10.0(Jan 2, 2022)

    What's new?

    • Added string support for country_code validation, thanks @uberswe for the PR.
    • Added support for alpha hex colours, thanks @nesty92 for the PR.
    • Added DNS RFC 1035 label format validator, thanks @0n1shi for the PR.
    • Added ULID validation, thanks @uberswe for the PR.
    • Added regex version (Semantic Versioning 2.0.0) validation, thanks @jtseng-godaddy for the PR.
    Source code(tar.gz)
    Source code(zip)
  • v10.9.0(Aug 8, 2021)

    What's new?

    • Fixed panic when use ru lang for translation, thanks @anisov for the PR
    • Add boolean baked-in validator to check a string value is a valid boolean representation, thanks @xvello for the PR
    • Document thread safety and recommended singleton usage, thanks @andrascz for the PR
    • Add validations for ISO 4217 currency codes, thanks @metinogurlu for the PR
    • Update universal-translator and locales dependencies to their latest versions.
    Source code(tar.gz)
    Source code(zip)
  • v10.8.0(Jul 26, 2021)

    What's new?

    • Updated deps to address security vulnerabilities discovered in them, thanks @saedx1 for the PR
    • Fix import and go get commands, thanks @BrianLeishman for the PR
    • Added new JWT validation, thanks @steveorourke for the PR
    • Documentation fixes/updates, thanks @Nikachev for the PR
    • Add zh missing translations for some tags, thanks @SkyingzZ for the PR
    • Updated all deps to their latest versions.
    Source code(tar.gz)
    Source code(zip)
  • v10.7.0(Jul 8, 2021)

  • v10.6.2(Jul 8, 2021)

    What was fixed?

    • Fix map diving validation, thanks @echovl for the PR
    • Fix ja translation, thanks @masafumi-i for the PR
    • Fix README documentation, thanks @arx111 for the PR
    Source code(tar.gz)
    Source code(zip)
  • v10.6.1(May 12, 2021)

  • v10.6.0(May 6, 2021)

    What's new?

    • Added boolean support for required_if, required_unless and eqfield. Thanks @zane-deg for the PR
    • Added ability to validate map data. Thanks @zytell3301 for the PR
    • Added BIC ISO format validator. Thanks @yeexel for the PR

    Maintainers

    A section has been added to the README regarding a "request for maintainers". I am so happy that the community has embraced this project! and I think that now is a good time to bring on more maintainers to help support the growing user base for timely help, PR reviews and general support.

    Source code(tar.gz)
    Source code(zip)
  • v10.5.0(Apr 7, 2021)

  • v10.4.2(Apr 6, 2021)

    What was Fixed?

    • Add support for excluded_with on pointer fields Thanks @Jake-Convictional for the PR
    • Fix excludedWithoutAll comment. Thanks @jfrancisco0 for the PR
    • Fix accessing fields in composed structs. Thanks @Adimus11 for the PR
    • Error in spelling. Thanks @Qalifah for the PR
    • Fix StructLevel Parent(). Thanks @Torwang1 for the PR
    • Add missing corresponds to boolean value in nefield. Thanks @Doarakko for the PR
    • New official Documentation URL is README. Thanks @frederikhors for the PR
    • Remove version from installation and import in the README. Thanks @Serj1c for the PR
    • Fix extra text in error.go comment. Thanks @deikatsuo for the PR
    Source code(tar.gz)
    Source code(zip)
  • v10.4.1(Oct 17, 2020)

    What was fixed?

    Fixed an issue where if the param of a time.Durtion type is specified as an integer, denoting nanosecond precision, instead of time duration string the validation would panic introduced in https://github.com/go-playground/validator/pull/642

    The fix ensures it falls back to the previous expected behaviour.

    Source code(tar.gz)
    Source code(zip)
  • v10.4.0(Sep 27, 2020)

    What's new?

    Merged ton of PR's, thank you everyone for your contributions!

    • https://github.com/go-playground/validator/pull/667
    • https://github.com/go-playground/validator/pull/666
    • https://github.com/go-playground/validator/pull/664
    • https://github.com/go-playground/validator/pull/658
    • https://github.com/go-playground/validator/pull/657
    • https://github.com/go-playground/validator/pull/644
    • https://github.com/go-playground/validator/pull/642
    • https://github.com/go-playground/validator/pull/641
    • https://github.com/go-playground/validator/pull/635
    • https://github.com/go-playground/validator/pull/630
    • https://github.com/go-playground/validator/pull/620
    • https://github.com/go-playground/validator/pull/615
    • https://github.com/go-playground/validator/pull/613
    Source code(tar.gz)
    Source code(zip)
  • v10.3.0(May 21, 2020)

    What's New/Fixed?

    New

    • Run tests on more recent Go version, thanks @psampaz for the PR
    • List validations in man README, thanks @psampaz for the PR
    • Updated godoc link, thanks @psampaz for the PR
    • Added Spanish translations, thanks @alfonsoprado for the PR
    • Add startsnotwith & endsnotwith validations, thanks @metalinspired for the PR
    • Fix some gramatical errors, thanks @erikaleigh for the PR
    • Add missing zh translations, thanks @cncal for the PR
    • Update zh datetime translation, thanks @fourcels for the PR

    Fixed

    • Fixed rfc952 regex, thanks @amiraliucsc for the PR
    • Add number validation to the docs, thanks @johnbailon for the PR
    • Allow number on FQDN, thanks @Giulianos for the PR
    Source code(tar.gz)
    Source code(zip)
  • v10.2.0(Feb 9, 2020)

    What's new?

    • Added DateTime validation, thanks @psampaz for the PR
    • Added JSON validation, thanks @psampaz for the PR
    • Added Hostname + Port validation, thanks @terala for the PR
    • Added Russion Translations validation, thanks @Rustery for the PR
    • Fixed typo in documentation, thanks @shenyiling for the PR
    • Added lowercase and uppercase validations, thanks @psampaz for the PR
    Source code(tar.gz)
    Source code(zip)
  • v10.1.0(Dec 25, 2019)

    What's new?

    🎄 Merry Christmas: 🎄

    🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁

    • Added GetTag functionality to the FieldLevel interface. Thanks @LRichi for the PR
    • Extended Isunique functionality to handle the uniqueness of struct fields in an array/slice. Thanks @shihanng for the PR
    • Improved documentation for custom functions. Thanks @skateinmars for the PR
    • Added e.164 phone number validation. Thanks @taybart for the PR
    • Optimize isurl nill error check, Thanks @whatvn for the PR
    • Remove unecessary casting in example, Thanks @Streppel for the PR
    • Improve accuracy of the datauri validation regex, Thanks @JonathanWThom for the PR
    • Add boolean type support for the eq validator, Thanks @ghost for the PR
    • Punctuation fix to the CONTRIBUTING.md, Thanks @sclaire-1 for the PR
    • Added ability to validate oneof for space-separated strings, Thanks @JonathanWThom for the PR
    Source code(tar.gz)
    Source code(zip)
  • v9.31.0(Dec 25, 2019)

    What's new?

    As of 2019-12-24 v9 is entering maintenance mode. Please direct all PR's to master.

    But before this happens, 🎄 Merry Christmas: 🎄

    🎁 🎁 🎁 🎁 🎁 🎁 🎁 🎁

    • Added GetTag functionality to the FieldLevel interface. Thanks @LRichi for the PR
    • Extended Isunique functionality to handle the uniqueness of struct fields in an array/slice. Thanks @shihanng for the PR
    • Improved documentation for custom functions. Thanks @skateinmars for the PR
    • Added e.164 phone number validation. Thanks @taybart for the PR
    Source code(tar.gz)
    Source code(zip)
  • v9.30.2(Nov 25, 2019)

  • v10.0.1(Nov 17, 2019)

  • v9.30.1(Nov 17, 2019)

    What was fixed?

    Backported some fixes from v10 for the required_with* validation functions.

    P.S. I highly recommending updating to v10 which is just v9 updated to use Go Modules and std import paths rather than gopkg.in. I will be putting v9 into maintenance mode soon as I don't have the bandwidth to maintain both v10 & v9.

    Source code(tar.gz)
    Source code(zip)
  • v10.0.0(Nov 11, 2019)

    What's new?

    • Updated to Go Modules
    • Updated deps to use their Go Modules versions.

    I wanted v10 to have a bunch of new functionality for everyone but Go Modules has forced my hand a bit.

    Source code(tar.gz)
    Source code(zip)
  • v9.30.0(Sep 29, 2019)

    What's new?

    • Added Turkish translations, thanks @UgurAsaner for the PR!
    • Cleaned up linting.

    What was fixed?

    • Fixed bad import path, thanks @teejays for the PR!
    • Fixed all required_with* behaviour, there were some issues with pointers.
    Source code(tar.gz)
    Source code(zip)
  • v9.29.1(Jul 12, 2019)

  • v9.29.0(May 23, 2019)

    What's new?

    • Updated the hostname regex to support uppercase letters, thanks @Zeroen for the PR

    Some new and exciting validators have been added, thanks @mashmooli for the PR

    • required_with
    • required_with_all
    • required_without
    • required_without_all

    please see the docs for usage instructions!

    Source code(tar.gz)
    Source code(zip)
  • v9.28.0(Mar 31, 2019)

    What's new?

    Huge shout out to the community for all the help!

    • Added new section for non-standard validations here from PR, thanks @andreiavrammsd!
      • these non standard validations will not be part of the beked in validations but rather a place for the community to put one-off validations that others may find useful and can register them as needed.
    • Updsated the SSN regex to handle more use cases in PR, thanks @rucas!
    • Added startswith snd endswith validations in PR, thanks @thcipriani!
    • Fixed a typo in the struct level example in PR, thanks @masseelch!
    • Updated the docs to include the uuid_rfc4122 validations in PR, thanks @alexbilbie!
    • Updated the email validations regex to handle a couple of failing real-world cases in PR, thanks @benpaxton-hf!
    Source code(tar.gz)
    Source code(zip)
  • v9.27.0(Feb 12, 2019)

    What new?

    • Added Validation for directories dir, thanks @agalal for the PR
    • Extended longitude + latitude validation to numbers, thanks @RaMin0 for the PR
    • Corrected a bunch of typos and documentation, thanks @sssinsi, @Esslamb and @kszafran for you PR's
    Source code(tar.gz)
    Source code(zip)
  • v9.26.0(Jan 28, 2019)

  • v9.25.0(Jan 9, 2019)

    What's new?

    Add baked in validators for containsfield and excludesfield, thanks @fharding1 for the PR

    What was fixed

    Fixed Japanese translations, thanks @akm for the PR

    Source code(tar.gz)
    Source code(zip)
  • v9.24.0(Dec 8, 2018)

    What's new?

    • Added URN validation, thanks @leodido for the PR
    • Added Japanese translations!!! 😍 , thanks @akm for the PR

    What was fixed?

    • Corrected imports in the pt_BR translation, thanks @AGPDev for the PR
    • Added missing translation for unique validation, thanks @holyspectral for the PR
    Source code(tar.gz)
    Source code(zip)
  • v9.23.0(Nov 4, 2018)

    What's new?

    • Added automatic pointer downgrade for RegisterStructValidation, thanks @suekto-andreas for the PR
    • Added Indonesian translations, thanks @sulthonzh for the PR
    Source code(tar.gz)
    Source code(zip)
Owner
Go Playgound
multiple packages, libraries and programs to further the advancement of Go!
Go Playgound
An interesting go struct tag expression syntax for field validation, etc.

go-tagexpr An interesting go struct tag expression syntax for field validation, etc. Usage Validator: A powerful validator that supports struct tag ex

Bytedance Inc. 1.2k Jul 4, 2022
An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.

ozzo-validation Description ozzo-validation is a Go package that provides configurable and extensible data validation capabilities. It has the followi

Ozzo Framework 2.8k Jul 1, 2022
Struct validation using tags

Govalid Use Govalid to validate structs. Documentation For full documentation see pkg.go.dev. Example package main import ( "fmt" "log" "strings"

Travis Harmon 29 May 14, 2022
Library providing opanapi3 and Go types for store/validation and transfer of ISO-4217, ISO-3166, and other types.

go-types This library has been created with the purpose to facilitate the store, validation, and transfer of Go ISO-3166/ISO-4217/timezones/emails/URL

Mikalai Konan 12 Feb 8, 2022
Swagger builder and input validation for Go servers

crud A Swagger/OpenAPI builder and validation library for building HTTP/REST APIs. Heavily inspired by hapi and the hapi-swagger projects. No addition

Jake Coffman 34 May 20, 2022
Go package containing implementations of efficient encoding, decoding, and validation APIs.

encoding Go package containing implementations of encoders and decoders for various data formats. Motivation At Segment, we do a lot of marshaling and

Segment 852 Jun 29, 2022
Validate Golang request data with simple rules. Highly inspired by Laravel's request validation.

Validate golang request data with simple rules. Highly inspired by Laravel's request validation. Installation Install the package using $ go get githu

Saddam H 1.1k Jun 26, 2022
Opinionated go to validation library

?? valeed Your opinionated go-to validation library. Struct tag-based. Validate here, validate there, validate everywhere. Sleek and simple validation

Avré Barra 1 Oct 20, 2021
Simple module for validation inn control number

simple module for validation inn control number

Pavel 0 Nov 18, 2021
Gin Middleware to extract json tag value from playground validator's errors validation

Json Tag Extractor for Go-Playground Validator This is Gin Middleware that aim to extract json tag and than store it to FieldError.Field() object. Ins

Muhamad Surya Iksanudin 0 Jan 14, 2022
Validator - Replace the validation framework used by gin

validator Replace the validation framework used by gin replace mod:replace githu

null 2 Jan 18, 2022
:balloon: A lightweight struct validator for Go

gody Go versions supported Installation go get github.com/guiferpa/gody/v2 Usage package main import ( "encoding/json" "fmt" "net/http"

Guilherme Paixão 60 Jun 27, 2022
[Go] Package of validators and sanitizers for strings, numerics, slices and structs

govalidator A package of validators and sanitizers for strings, structs and collections. Based on validator.js. Installation Make sure that Go is inst

Alex Saskevich 5.4k Jul 5, 2022
Provide check digit algorithms and calculators written in Go

checkdigit About Provide check digit algorithms and calculators written by Go. Provided methods Algorithms Luhn Verhoeff Damm Calculators ISBN-10 ISBN

Osamu TONOMORI 89 May 16, 2022
A norms and conventions validator for Terraform

This tool will help you ensure that a terraform folder answer to your norms and conventions rules. This can be really useful in several cases : You're

Thibault Hazelart 78 May 6, 2022
The Hyperscale InputFilter library provides a simple inputfilter chaining mechanism by which multiple filters and validator may be applied to a single datum in a user-defined order.

Hyperscale InputFilter Branch Status Coverage master The Hyperscale InputFilter library provides a simple inputfilter chaining mechanism by which mult

Hyperscale Stack 0 Oct 20, 2021
💯 Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving

Package validator implements value validations for structs and individual fields based on tags.

Flamego 12 Feb 16, 2022
Golang parameter validation, which can replace go-playground/validator, includes ncluding Cross Field, Map, Slice and Array diving, provides readable,flexible, configurable validation.

Checker 中文版本 Checker is a parameter validation package, can be use in struct/non-struct validation, including cross field validation in struct, elemen

Liang Yaopei 70 Jun 29, 2022
Convert struct, slice, array, map or others for Golang

XConv zh-CN XConv is a golang type convertor. It convert any value between types (base type, struct, array, slice, map, etc.) Features Convert between

null 16 Dec 9, 2021
Takes an integer array, returns the array sorted and the number of inversions in the array

Takes an integer slice, returns the slice sorted and the number of inversions in the slice

SaSo 0 Jan 25, 2022
💪 Helper Utils For The Go: string, array/slice, map, format, cli, env, filesystem, test and more.

?? Helper Utils For The Go: string, array/slice, map, format, cli, env, filesystem, test and more. Go 的一些工具函数,格式化,特殊处理,常用信息获取等等

Gookit 839 Jun 29, 2022
An interesting go struct tag expression syntax for field validation, etc.

go-tagexpr An interesting go struct tag expression syntax for field validation, etc. Usage Validator: A powerful validator that supports struct tag ex

Bytedance Inc. 1.2k Jul 4, 2022
An interesting go struct tag expression syntax for field validation, etc.

An interesting go struct tag expression syntax for field validation, etc.

Bytedance Inc. 1.2k Jul 5, 2022
An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.

ozzo-validation Description ozzo-validation is a Go package that provides configurable and extensible data validation capabilities. It has the followi

Ozzo Framework 2.8k Jul 1, 2022
My clean Go solution that's faster than 100%, takes up less memory than 100%.

Remove-element My very clean Go solution that's faster than 100% of all solutions on Leetcode. Leetcode Challenge: "Given an integer array nums and an

Daniel Pickens 0 Dec 24, 2021
G-array is a GoLang library, that contains the generic function to do the array operations.

G-array Garray is a library written in Go (Golang). Which have a collection of functions to do the array operations. Installation To install G-array p

99x 2 May 24, 2022
Repo Tugas Basic Programming Part 4(Complexity Analysis, Array, Slice, Function) ALTA Immersive BE5

Cara mengerjakan tugas hari ke 4 clone project ini dengan cara git clone https://github.com/ALTA-Immersive-BE5/Basic-Programming-Part4.git setelah cl

null 0 Dec 15, 2021