GithubHelp home page GithubHelp logo

go-playground / validator Goto Github PK

View Code? Open in Web Editor NEW
16.1K 119.0 1.3K 2.04 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 Issues

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")

Add or option

add or option to the tag section for example

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

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,
    })
}

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

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.

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

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.

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{}){
...
}

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 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

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).

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.

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 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.

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.

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)

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 )

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

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.

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

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.

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 coverage badge

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

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


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

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 ?

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.

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.

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.