GithubHelp home page GithubHelp logo

go-playground / validator Goto Github PK

View Code? Open in Web Editor NEW
15.6K 117.0 1.3K 1.87 MB

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

License: MIT License

Go 99.98% Makefile 0.02%
validation translation error-handling

validator's Introduction

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 returns 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://pkg.go.dev/github.com/go-playground/validator/v10 for detailed usage docs.

Examples:

Baked-in Validations

Special Notes:

  • If new to using validator it is highly recommended to initialize it using the WithRequiredStructEnabled option which is opt-in to new behaviour that will become the default behaviour in v11+. See documentation for more details.
validate := validator.New(validator.WithRequiredStructEnabled())

Fields:

Tag Description
eqcsfield Field Equals Another Field (relative)
eqfield Field Equals Another Field
fieldcontains Check the indicated characters are present in the Field
fieldexcludes Check the indicated characters are not present in the field
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
http_url HTTP 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
boolean Boolean
contains Contains
containsany Contains Any
containsrune Contains Rune
endsnotwith Ends Not With
endswith Ends With
excludes Excludes
excludesall Excludes All
excludesrune Excludes Rune
lowercase Lowercase
multibyte Multi-Byte Characters
number Number
numeric Numeric
printascii Printable ASCII
startsnotwith Starts Not With
startswith Starts With
uppercase Uppercase

Format:

Tag Description
base64 Base64 String
base64url Base64URL String
base64rawurl Base64RawURL String
bic Business Identifier Code (ISO 9362)
bcp47_language_tag Language tag (BCP 47)
btc_addr Bitcoin Address
btc_addr_bech32 Bitcoin Bech32 Address (segwit)
credit_card Credit Card Number
mongodb MongoDB ObjectID
cron Cron
spicedb SpiceDb ObjectID/Permission/Type
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
issn International Standard Serial Number
iso3166_1_alpha2 Two-letter country code (ISO 3166-1 alpha-2)
iso3166_1_alpha3 Three-letter country code (ISO 3166-1 alpha-3)
iso3166_1_alpha_numeric Numeric country code (ISO 3166-1 numeric)
iso3166_2 Country subdivision code (ISO 3166-2)
iso4217 Currency code (ISO 4217)
json JSON
jwt JSON Web Token (JWT)
latitude Latitude
longitude Longitude
luhn_checksum Luhn Algorithm Checksum (for strings and (u)int)
postcode_iso3166_alpha2 Postcode
postcode_iso3166_alpha2_field Postcode
rgb RGB String
rgba RGBA String
ssn Social Security Number SSN
timezone Timezone
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
md4 MD4 hash
md5 MD5 hash
sha256 SHA256 hash
sha384 SHA384 hash
sha512 SHA512 hash
ripemd128 RIPEMD-128 hash
ripemd128 RIPEMD-160 hash
tiger128 TIGER128 hash
tiger160 TIGER160 hash
tiger192 TIGER192 hash
semver Semantic Versioning 2.0.0
ulid Universally Unique Lexicographically Sortable Identifier ULID
cve Common Vulnerabilities and Exposures Identifier (CVE id)

Comparisons:

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

Other:

Tag Description
dir Existing Directory
dirpath Directory Path
file Existing File
filepath File Path
image Image
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_if Excluded If
excluded_unless Excluded Unless
excluded_with Excluded With
excluded_with_all Excluded With All
excluded_without Excluded Without
excluded_without_all Excluded Without All
unique Unique

Aliases:

Tag Description
iscolor hexcolor|rgb|rgba|hsl|hsla
country_code iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric

Benchmarks

Run on MacBook Pro (15-inch, 2017) go version go1.10.2 darwin/amd64
go version go1.21.0 darwin/arm64
goos: darwin
goarch: arm64
pkg: github.com/go-playground/validator/v10
BenchmarkFieldSuccess-8                                         33142266                35.94 ns/op            0 B/op          0 allocs/op
BenchmarkFieldSuccessParallel-8                                 200816191                6.568 ns/op           0 B/op          0 allocs/op
BenchmarkFieldFailure-8                                          6779707               175.1 ns/op           200 B/op          4 allocs/op
BenchmarkFieldFailureParallel-8                                 11044147               108.4 ns/op           200 B/op          4 allocs/op
BenchmarkFieldArrayDiveSuccess-8                                 6054232               194.4 ns/op            97 B/op          5 allocs/op
BenchmarkFieldArrayDiveSuccessParallel-8                        12523388                94.07 ns/op           97 B/op          5 allocs/op
BenchmarkFieldArrayDiveFailure-8                                 3587043               334.3 ns/op           300 B/op         10 allocs/op
BenchmarkFieldArrayDiveFailureParallel-8                         5816665               200.8 ns/op           300 B/op         10 allocs/op
BenchmarkFieldMapDiveSuccess-8                                   2217910               540.1 ns/op           288 B/op         14 allocs/op
BenchmarkFieldMapDiveSuccessParallel-8                           4446698               258.7 ns/op           288 B/op         14 allocs/op
BenchmarkFieldMapDiveFailure-8                                   2392759               504.6 ns/op           376 B/op         13 allocs/op
BenchmarkFieldMapDiveFailureParallel-8                           4244199               286.9 ns/op           376 B/op         13 allocs/op
BenchmarkFieldMapDiveWithKeysSuccess-8                           2005857               592.1 ns/op           288 B/op         14 allocs/op
BenchmarkFieldMapDiveWithKeysSuccessParallel-8                   4400850               296.9 ns/op           288 B/op         14 allocs/op
BenchmarkFieldMapDiveWithKeysFailure-8                           1850227               643.8 ns/op           553 B/op         16 allocs/op
BenchmarkFieldMapDiveWithKeysFailureParallel-8                   3293233               375.1 ns/op           553 B/op         16 allocs/op
BenchmarkFieldCustomTypeSuccess-8                               12174412                98.25 ns/op           32 B/op          2 allocs/op
BenchmarkFieldCustomTypeSuccessParallel-8                       34389907                35.49 ns/op           32 B/op          2 allocs/op
BenchmarkFieldCustomTypeFailure-8                                7582524               156.6 ns/op           184 B/op          3 allocs/op
BenchmarkFieldCustomTypeFailureParallel-8                       13019902                92.79 ns/op          184 B/op          3 allocs/op
BenchmarkFieldOrTagSuccess-8                                     3427260               349.4 ns/op            16 B/op          1 allocs/op
BenchmarkFieldOrTagSuccessParallel-8                            15144128                81.25 ns/op           16 B/op          1 allocs/op
BenchmarkFieldOrTagFailure-8                                     5913546               201.9 ns/op           216 B/op          5 allocs/op
BenchmarkFieldOrTagFailureParallel-8                             9810212               113.7 ns/op           216 B/op          5 allocs/op
BenchmarkStructLevelValidationSuccess-8                         13456327                87.66 ns/op           16 B/op          1 allocs/op
BenchmarkStructLevelValidationSuccessParallel-8                 41818888                27.77 ns/op           16 B/op          1 allocs/op
BenchmarkStructLevelValidationFailure-8                          4166284               272.6 ns/op           264 B/op          7 allocs/op
BenchmarkStructLevelValidationFailureParallel-8                  7594581               152.1 ns/op           264 B/op          7 allocs/op
BenchmarkStructSimpleCustomTypeSuccess-8                         6508082               182.6 ns/op            32 B/op          2 allocs/op
BenchmarkStructSimpleCustomTypeSuccessParallel-8                23078605                54.78 ns/op           32 B/op          2 allocs/op
BenchmarkStructSimpleCustomTypeFailure-8                         3118352               381.0 ns/op           416 B/op          9 allocs/op
BenchmarkStructSimpleCustomTypeFailureParallel-8                 5300738               224.1 ns/op           432 B/op         10 allocs/op
BenchmarkStructFilteredSuccess-8                                 4761807               251.1 ns/op           216 B/op          5 allocs/op
BenchmarkStructFilteredSuccessParallel-8                         8792598               128.6 ns/op           216 B/op          5 allocs/op
BenchmarkStructFilteredFailure-8                                 5202573               232.1 ns/op           216 B/op          5 allocs/op
BenchmarkStructFilteredFailureParallel-8                         9591267               121.4 ns/op           216 B/op          5 allocs/op
BenchmarkStructPartialSuccess-8                                  5188512               231.6 ns/op           224 B/op          4 allocs/op
BenchmarkStructPartialSuccessParallel-8                          9179776               123.1 ns/op           224 B/op          4 allocs/op
BenchmarkStructPartialFailure-8                                  3071212               392.5 ns/op           440 B/op          9 allocs/op
BenchmarkStructPartialFailureParallel-8                          5344261               223.7 ns/op           440 B/op          9 allocs/op
BenchmarkStructExceptSuccess-8                                   3184230               375.0 ns/op           424 B/op          8 allocs/op
BenchmarkStructExceptSuccessParallel-8                          10090130               108.9 ns/op           208 B/op          3 allocs/op
BenchmarkStructExceptFailure-8                                   3347226               357.7 ns/op           424 B/op          8 allocs/op
BenchmarkStructExceptFailureParallel-8                           5654923               209.5 ns/op           424 B/op          8 allocs/op
BenchmarkStructSimpleCrossFieldSuccess-8                         5232265               229.1 ns/op            56 B/op          3 allocs/op
BenchmarkStructSimpleCrossFieldSuccessParallel-8                17436674                64.75 ns/op           56 B/op          3 allocs/op
BenchmarkStructSimpleCrossFieldFailure-8                         3128613               383.6 ns/op           272 B/op          8 allocs/op
BenchmarkStructSimpleCrossFieldFailureParallel-8                 6994113               168.8 ns/op           272 B/op          8 allocs/op
BenchmarkStructSimpleCrossStructCrossFieldSuccess-8              3506487               340.9 ns/op            64 B/op          4 allocs/op
BenchmarkStructSimpleCrossStructCrossFieldSuccessParallel-8     13431300                91.77 ns/op           64 B/op          4 allocs/op
BenchmarkStructSimpleCrossStructCrossFieldFailure-8              2410566               500.9 ns/op           288 B/op          9 allocs/op
BenchmarkStructSimpleCrossStructCrossFieldFailureParallel-8      6344510               188.2 ns/op           288 B/op          9 allocs/op
BenchmarkStructSimpleSuccess-8                                   8922726               133.8 ns/op             0 B/op          0 allocs/op
BenchmarkStructSimpleSuccessParallel-8                          55291153                23.63 ns/op            0 B/op          0 allocs/op
BenchmarkStructSimpleFailure-8                                   3171553               378.4 ns/op           416 B/op          9 allocs/op
BenchmarkStructSimpleFailureParallel-8                           5571692               212.0 ns/op           416 B/op          9 allocs/op
BenchmarkStructComplexSuccess-8                                  1683750               714.5 ns/op           224 B/op          5 allocs/op
BenchmarkStructComplexSuccessParallel-8                          4578046               257.0 ns/op           224 B/op          5 allocs/op
BenchmarkStructComplexFailure-8                                   481585              2547 ns/op            3041 B/op         48 allocs/op
BenchmarkStructComplexFailureParallel-8                           965764              1577 ns/op            3040 B/op         48 allocs/op
BenchmarkOneof-8                                                17380881                68.50 ns/op            0 B/op          0 allocs/op
BenchmarkOneofParallel-8                                         8084733               153.5 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.

Maintainers

This project has grown large enough that more than one person is required to properly support the community. If you are interested in becoming a maintainer please reach out to me https://github.com/deankarn

validator's People

Contributors

akm avatar amiraliucsc avatar andreiavrammsd avatar ansel1 avatar deankarn avatar elias19r avatar foolin avatar giulianos avatar jahanviaggarwal avatar jnst avatar jonathanwthom avatar jservice-rvbd avatar krhubert avatar leodido avatar mashmooli avatar math-nao avatar nodivbyzero avatar noibar avatar psampaz avatar questofiranon avatar ramin0 avatar secake avatar senuphtyz avatar shihanng avatar suekto-andreas avatar taybart avatar teejays avatar vuon9 avatar zemzale avatar zhing avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

validator's Issues

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 for all using this library - is the hierarchical error structure useful?

Hello All!

Since implementing the "dive" tag, I have been questioning whether the hierarchical data structure is the best option, mainly because of the extra overhead and placeholder errors needed.

I could store the struct name, field name and name-spaced name on the field error and could just return a map of map[string]*FieldError where the key is the name-spaced name; with this approach I should be able to make validator even faster and more efficient.

my only concern is getting rid of the hierarchical functionality in case someone is using it or it would be beneficial to keep.

so should I just return a map of errors?

Update README

to highlight this library's unique features
showcase some benchmarks
and give a quick usage example ( just like in the godocs )

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

Add support to validate fields or structs nested within arrays, slices and maps

this was prompted by pull request gin-gonic/gin#224 for @manucorporat

add an additional tag called "dive", this will let the library know to dive into the array or slice; additionally any validations such as gt=0 that appear after dive can be applied to simple data types, while maintaining the validation on the actual array field before the dive tag.
i.e.

type Address struct {
    Location string `validate:"required"`
}

type User struct {
    Addresses    []*Address `validate:"gt=0,dive"`           // dive into the array/slice and validate Adress
    WorkingDays  []int      `validate:"eq=7,dive,eq=0|eq=1"` // validate there are exactly 7 array items and then dive into int array and validate that each value is either 0 or 1
}

Now the hard part

Need to figure out a way to store the errors within the StructErrors and FieldError struct's hierarchy; it's not enough to just throw an error, I need to store the error, what field it was on AND what index of the array or struct it was on so that I may display the error on the actual field within the application using this library ( like it is now )

it's further complicated by maps, because the key could be of just about any data type

and even more, what about arrays of arrays [][]int

Any suggestions are definitely welcome, I will just have to be creative.

Unable to get validator

This is what I get when I run go get , any idea what I am doing wrong ?

# gopkg.in/bluesuncorp/validator.v7
src/gopkg.in/bluesuncorp/validator.v7/validator.go:43: undefined: sync.Pool

V7 in the works!

What v7

I know I said v6 was intended to be long term stable, and it was, the breaking change is so small, but a breaking change non the less so v7 is underway, need to pass Validator instance into the validation functions themselves.

What's new and why do I care to update to v7?

Cross Struct field validation/comparison via tags
Currently you can validate that field say is greater than another on the same struct,but if you want to compare it to say a nested structs field you currently can do that, but requires a custom validator. V7 will allow for cross struct field validation without a custom validator but using tags for example:

type Inner struct {
  CreatedAt time.Time
}

type Outer struct {
  Inner *Inner
  CreatedAt time.Time `validate:"gtecsfield=Inner.CreatedAt"`
}

now := time.Now()

Inner := &Inner{
  CreatedAt: now,
}

outer := &Outer{
  Inner: inner,
  CreatedAt: now,
}

errs := validate.Struct(outer)
fmt.Println(errs)

no depth limit, will support Slices, Arrays, maps, structs, Slices of Slices.... basically and combination

so you just have to specify the field via the fully nested namespace. Will be keeping the old field validators as if only checking a field on the same struct will be faster than traversing, if it's not needed.

Add has and hasAny validators

Example:

This will allow a field, say username, to exclude a character or string.

And has any will exclude any of the characters provided

AndcontainsAny

Add Base 64 Validation

Regular expression for matching base64 encoded strings

base64
This validates that a string value contains a valid encoded base 64

(Usage: base64)

Add or option

add or option to the tag section for example

validate:"rgb|rgba" // so the field could be rgb or rgba

Investigate Caching

See if caching would speed up subsequent validations, if it makes a significant difference, add a cache option and set it to true by default. The option is to allow those that still require the lowest footprint possible, besides it's already fast.

**NOTE: be sure to grab the underlying type

v5.9 panic

Hi All,

I use github.com/gin/gin-gonic web framework, and the framework use your validator and i received panic every request. Here the panic log.

2015/06/28 19:32:07 Panic recovery -> runtime error: index out of range
/usr/local/go/src/runtime/panic.go:387 (0x466f18)
gopanic: reflectcall(unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))
/usr/local/go/src/runtime/panic.go:12 (0x4660ae)
panicindex: panic(indexError)
/root/go/src/gopkg.in/bluesuncorp/validator.v5/validator.go:369 (0x6dbd16)
/root/go/src/gopkg.in/bluesuncorp/validator.v5/validator.go:333 (0x6da7b2)
/root/go/src/gopkg.in/bluesuncorp/validator.v5/validator.go:324 (0x6da600)

How can i solve the problem?

Thanks.

V6 future Changes

Config Struct

Use a Config Struct for creating a new validator instance; this will allow more flexibility in adding new options without causing breaking changes

Name Updates

change AddFunction to RegisterValidator to be more idiomatic

Error Hierarchy

remove error hierarchy in favour of a map errors with key of name-spaced of error and FieldError, much like the Flatten() function does now. With this approach should be able to make the librayr, faster, more efficient and code more DRY.

Remove Deprecated methods

remove some deprecated methods, really only one and was only added to keep v5 compatibility and so has been noted about it's removal in v6 from the get go.

Add Cross Field Validation

V2 - New Version - Breaking Change

This will be a breaking change because the validation function definition has to change, but will be no more complicated than is is now to add custom functions.

Dilema

If I want to compare a Start and End date or validate any field compared to another ( maybe even in a nested struct scenario ) there is currently no way to reference the other fields or structs.

Solution

Pass the Top Level struct ( when validating by struct ) to the validation functions.

Other Changes

Add an optional function for validating by field alone to also pass in a top level and/or nested containing struct or other field value, for full rounded functionality.

NOTES

  1. Since people will name their fields differently and have unique and specific needs, there will most likely never be any baked in validation functions for using this new cross validation ability, however it will allow people to create their own reusable validation functions and ensure all their validation code remains in the same place.

PROMPTING REQUIREMENT

I needed the ability to validate that when saving a user record to the database that their username field was unique, pretty standard look into the database and see if there is already a record with this username.
The issue comes when updating a record, a record will exist with the current username(assuming it wasn't changed) but it is valid to save because we are just updating the existing record; I needed the ability to check that a user record exists and the user I'm validating's unique ID is not equal to that records unique ID - which is contained within the struct the username field belongs to.

Interface still makes validator panic

Validator still crashes when passing struct with interface{}.

2015/07/09 11:44:48 Panic recovery -> Invalid validation tag on field C
/usr/local/Cellar/go/1.4.2/libexec/src/runtime/panic.go:387 (0x13ee8)
    gopanic: reflectcall(unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))
/Users/manu/repos/go/src/gopkg.in/bluesuncorp/validator.v5/validator.go:686 (0x207ce8)
    (*Validate).fieldWithNameAndValue: panic(fmt.Sprintf("Invalid validation tag on field %s", name))
/Users/manu/repos/go/src/gopkg.in/bluesuncorp/validator.v5/validator.go:531 (0x204b51)
    (*Validate).structRecursive: if fieldError := v.fieldWithNameAndValue(top, current, valueField.Interface(), cField.tag, cField.name, false, nil); fieldError != nil {
/Users/manu/repos/go/src/gopkg.in/bluesuncorp/validator.v5/validator.go:387 (0x203ac2)
    (*Validate).structRecursive: return v.structRecursive(top, current, structValue.Elem().Interface())
/Users/manu/repos/go/src/gopkg.in/bluesuncorp/validator.v5/validator.go:378 (0x203910)
    (*Validate).Struct: return v.structRecursive(s, s, s)
/Users/manu/repos/go/src/github.com/gin-gonic/gin/binding/default_validator.go:20 (0xb6ca7)
    (*defaultValidator).ValidateStruct: if err := v.validate.Struct(obj); err != nil {
/Users/manu/repos/go/src/github.com/gin-gonic/gin/binding/binding.go:62 (0xb6bf9)
    validate: return Validator.ValidateStruct(obj)
/Users/manu/repos/go/src/github.com/gin-gonic/gin/binding/json.go:24 (0xb820e)
    jsonBinding.Bind: return validate(obj)
<autogenerated>:6 (0xb8927)
/Users/manu/repos/go/src/github.com/gin-gonic/gin/context.go:270 (0x400c2)
    (*Context).BindWith: if err := b.Bind(c.Request, obj); err != nil {
/Users/manu/repos/go/src/github.com/gin-gonic/gin/context.go:259 (0x3ff7e)
    (*Context).Bind: return c.BindWith(obj, b)
/Users/manu/test2/main.go:18 (0x2168)
    Create: c.Bind(&a)
/Users/manu/repos/go/src/github.com/gin-gonic/gin/context.go:95 (0x3f2b0)
    (*Context).Next: c.handlers[c.index](c)
/Users/manu/repos/go/src/github.com/gin-gonic/gin/logger.go:56 (0x4f532)
    func.008: c.Next()
/Users/manu/repos/go/src/github.com/gin-gonic/gin/context.go:95 (0x3f2b0)
    (*Context).Next: c.handlers[c.index](c)
/Users/manu/repos/go/src/github.com/gin-gonic/gin/recovery.go:43 (0x4ff12)
    func.010: c.Next()
/Users/manu/repos/go/src/github.com/gin-gonic/gin/context.go:95 (0x3f2b0)
    (*Context).Next: c.handlers[c.index](c)
/Users/manu/repos/go/src/github.com/gin-gonic/gin/gin.go:292 (0x45493)
    (*Engine).handleHTTPRequest: context.Next()
/Users/manu/repos/go/src/github.com/gin-gonic/gin/gin.go:273 (0x45167)
    (*Engine).ServeHTTP: engine.handleHTTPRequest(c)
/usr/local/Cellar/go/1.4.2/libexec/src/net/http/server.go:1703 (0x7e45a)
    serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/usr/local/Cellar/go/1.4.2/libexec/src/net/http/server.go:1204 (0x7bcd7)
    (*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
/usr/local/Cellar/go/1.4.2/libexec/src/runtime/asm_amd64.s:2232 (0x3e0b1)
    goexit: 

code:

package main

import "github.com/gin-gonic/gin"

type MyStruct struct {
    A, B string
    C    interface{}
}

func main() {
    router := gin.Default()
    router.POST("/post", Create)
    router.Run(":8080")
}

func Create(c *gin.Context) {
    var a MyStruct
    c.Bind(&a)
    c.JSON(200, gin.H{
        "bind": a,
    })
}

Add new tag "structonly"

a flag is needed to identify that validation should run for a struct i.e. struct is required but not validate it's containing fields.

example:
type Inner struct{
Test string validate:"len=5"
}

type Outer struct{
InnerStruct Inner validate:"required,structonly"
}

in the above example InnerStruct will validate on the required, but Inner's Test field will not be validated.

Can't download

The get command hangs:
$ go get -v -u gopkg.in/bluesuncorp/validator.v5
Fetching https://gopkg.in/bluesuncorp/validator.v5?go-get=1
Parsing meta tags from https://gopkg.in/bluesuncorp/validator.v5?go-get=1 (status code 200)
get "gopkg.in/bluesuncorp/validator.v5": found meta tag main.metaImport{Prefix:"gopkg.in/bluesuncorp/validator.v5", VCS:"git", RepoRoot:"https://gopkg.in/bluesuncorp/validator.v5"} at https://gopkg.in/bluesuncorp/validator.v5?go-get=1
gopkg.in/bluesuncorp/validator.v5 (download)

StructPartial() doesn't complain about invalid fields

I would assume that if I pass in a bogus field name into StructPartial it complains about it being missing.

type Foo struct {
    Field string
}

var foo Foo

err := validator.StructPartial(foo, "Bogus")

err is nil unfortunately.

Remove internal validator

Breaking change create branch v3

internal validator was a bad idea, each package you include it in a new internal validator is used and custom functions have to be re-added and so forth; it is better to create a new one that the application/user can manage and pass around if they like.

Projects using this - would you like to be linked from the README

Hello everyone,

I was looking to start a list of projects on my README that are using this library in the hopes of not only satisfying my own curiosity, but also to promote your works and hopefully draw others to both of our works.

So please comment with the link to your project, if you want, and let me know with a +1 if it would be alright to add your project to the README, otherwise I will assume you do not wish to be added.

Thanks in advance!

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.

Error() prints too many end-lines

Since the errors reported by validator will be likely sent through JSON or printed in a log:
I would recommend to remove most of the end-lines:

Struct: Field validation for "Id" failed on the "required" tag

instead of:

Struct:
Field validation for "Id" failed on the "required" tag


Help with Logo creation

Summary

In short I'm no artist, I'm looking to create a logo for this library; hopefully someone can help.

Criteria: NONE

Nice to Have

  • go/golang gopher included
  • some reference to Firefly ( hence the organization name bluesuncorp ) browncoats forever!

Please upload images within your comments

Add eq and eqfield validators

eqfield would be useful comparing that password and confirm password are equal.

eq would be useful in combination with the 'or' ( | ) operator to ensure that a value is one of a specific value.

Cross Field OR validation

Is it possible to validate that on a given struct at least one of two options is required? I often have a struct where as long as one out of 2 of the fields are filled in, it will pass validation. One basic example would be having a username field and an email field (just a basic example though).

Is there any possibility to specify custom message for error?

Hey
Thank you for your great library. Please see the subject ;)
Especially if I have custom validation tag, I want to attach my own message.

Yes, I have a map of errors and I can do wherever I want with it. But, I mean maybe it is better to have something more userfriendly errors. Like "Fielt a should be 5 or more characters length". I mean custom errors for each tag.

Thank you

Add coverage badge

I have always maintained 100% test coverage, just thought I'd add the badge and automated test to the build tests.

Add StructPartial function to allow for conditional validation

To Add

Add StructPartial function to allow for conditional validation. some people require contextual validation, this will give them the option to include or exclude fields on the struct for their needs.

// exclude - will determine if the fields in map will be included or excluded, 
// whichever there are less of would make sense
// map Key will be the Field name and using struct{} as value to limit memory, 
// consumes less memory than bool.
function StructPartial(current interface{}, exclude bool, fields map[string]struct{}){
...
}

Add ne and nefield functions

sometimes you want to make sure that data is not equal to any other, for example for another project I need to store color codes which represent different application states, and need to verify that none of the colors are equal.

Possible inversion of GteField and LteField

It appears that the GteField and LteField validators are inverted and comparing the wrong less/greater than.

Ex. Failing on "createdAt" : ISODate("2014-10-15T16:30:10.000Z"), "updatedAt" : ISODate("2015-03-20T14:45:06.061Z")

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.