go-playground / validator Goto Github PK
View Code? Open in Web Editor NEW:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
License: MIT License
:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
License: MIT License
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.
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")
for example if I want to excludeall= @ <- space and @
the space is currently being trimmed away
add or option to the tag section for example
validate:"rgb|rgba"
// so the field could be rgb or rgba
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,
})
}
In short I'm no artist, I'm looking to create a logo for this library; hopefully someone can help.
Add more baked in functions for regular checking scenarios
is alphanumeric, is number etc... and their associated testing scenarios
Add returning of Type along with Kind to differentiate struct types such as struct vs time.Time for message handling within the referencing application.
Recursive Structs should be validated on ValidateStructRecursive rather than ValidateStruct
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.
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.
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 one more param passed to validation functions which contains the current level struct.
although a small change, it is breaking so a new version v4 branch will be created to be consistent; it will allow for some other minor changes to be made at the same time for efficiency.
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. 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{}){
...
}
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 automated testing with travis ci
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
when a nested struct is defined as a pointer and is of nil value validation is failing
must also handle the required and omitempty tags, sometimes nil is ok
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 ability to validate interfaces
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.
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.
Pass the Top Level struct ( when validating by struct ) to the validation functions.
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.
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.
look into reusing these structs, using channels, to reduce memory allocations even further
The Flatten() function was overlooked to when adding the new dive funtionality
Use a Config Struct for creating a new validator instance; this will allow more flexibility in adding new options without causing breaking changes
change AddFunction to RegisterValidator to be more idiomatic
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 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.
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.
Modify Error structs to comply with the Error interface
code cleanup to meet coverage tests using go test -cover
add to gt, gte, le and lte
this will allow generic Start vs End Time validation and Range Validation
example:
Start
validate:"lt=End"
<-- will look for field "End" on top level struct and validate "Start" is before "End"
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.
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)
I want to use Sourcegraph for validator code search, browsing, and usage examples. Can an admin enable Sourcegraph for this repository? Just go to https://sourcegraph.com/github.com/bluesuncorp/validator. (It should only take 30 seconds.)
Thank you!
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?
to highlight this library's unique features
showcase some benchmarks
and give a quick usage example ( just like in the godocs )
Add Testing Scenarios to all existing baked in functions.
This is just a suggestion: so instead of implementing your own pool:
https://github.com/bluesuncorp/validator/blob/v5/validator.go#L47-L52
it could be a good idea to use the built-in pool implementation of the sync package.
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
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.
results will be a flattened array with struct names and field name combined like a namespace.
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
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.
There are too many variables to take into account for passing in a time to be validated against or doing anything other than UTC time without creating a custom function for your particular application.
Dates should be stored within the database as UTC, if anyone disagrees they'll have write your own validation function to handle your specific scenario.
Regular expression for matching base64 encoded strings
base64
This validates that a string value contains a valid encoded base 64
(Usage: base64)
I have always maintained 100% test coverage, just thought I'd add the badge and automated test to the build tests.
for example excludesall=!@#$%^&*()_+,=
I suspect comma will have to be a special case, maybe use it's hex equivalent and replace while processing
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
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
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 ?
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
}
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.
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.