-
Notifications
You must be signed in to change notification settings - Fork 8.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix(binding): Expose validator engine used by the default Validator #1277
Merged
appleboy
merged 3 commits into
gin-gonic:master
from
sudo-suhas:feat/expose-validator-engine
Mar 29, 2018
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
## Struct level validations | ||
|
||
Validations can also be registered at the `struct` level when field level validations | ||
don't make much sense. This can also be used to solve cross-field validation elegantly. | ||
Additionally, it can be combined with tag validations. Struct Level validations run after | ||
the structs tag validations. | ||
|
||
### Example requests | ||
|
||
```shell | ||
# Validation errors are generated for struct tags as well as at the struct level | ||
$ curl -s -X POST http://localhost:8085/user \ | ||
-H 'content-type: application/json' \ | ||
-d '{}' | jq | ||
{ | ||
"error": "Key: 'User.Email' Error:Field validation for 'Email' failed on the 'required' tag\nKey: 'User.FirstName' Error:Field validation for 'FirstName' failed on the 'fnameorlname' tag\nKey: 'User.LastName' Error:Field validation for 'LastName' failed on the 'fnameorlname' tag", | ||
"message": "User validation failed!" | ||
} | ||
|
||
# Validation fails at the struct level because neither first name nor last name are present | ||
$ curl -s -X POST http://localhost:8085/user \ | ||
-H 'content-type: application/json' \ | ||
-d '{"email": "[email protected]"}' | jq | ||
{ | ||
"error": "Key: 'User.FirstName' Error:Field validation for 'FirstName' failed on the 'fnameorlname' tag\nKey: 'User.LastName' Error:Field validation for 'LastName' failed on the 'fnameorlname' tag", | ||
"message": "User validation failed!" | ||
} | ||
|
||
# No validation errors when either first name or last name is present | ||
$ curl -X POST http://localhost:8085/user \ | ||
-H 'content-type: application/json' \ | ||
-d '{"fname": "George", "email": "[email protected]"}' | ||
{"message":"User validation successful."} | ||
|
||
$ curl -X POST http://localhost:8085/user \ | ||
-H 'content-type: application/json' \ | ||
-d '{"lname": "Contanza", "email": "[email protected]"}' | ||
{"message":"User validation successful."} | ||
|
||
$ curl -X POST http://localhost:8085/user \ | ||
-H 'content-type: application/json' \ | ||
-d '{"fname": "George", "lname": "Costanza", "email": "[email protected]"}' | ||
{"message":"User validation successful."} | ||
``` | ||
|
||
### Useful links | ||
|
||
- Validator docs - https://godoc.org/gopkg.in/go-playground/validator.v8#Validate.RegisterStructValidation | ||
- Struct level example - https://github.com/go-playground/validator/blob/v8.18.2/examples/struct-level/struct_level.go | ||
- Validator release notes - https://github.com/go-playground/validator/releases/tag/v8.7 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
package main | ||
|
||
import ( | ||
"net/http" | ||
"reflect" | ||
|
||
"github.com/gin-gonic/gin" | ||
"github.com/gin-gonic/gin/binding" | ||
validator "gopkg.in/go-playground/validator.v8" | ||
) | ||
|
||
// User contains user information. | ||
type User struct { | ||
FirstName string `json:"fname"` | ||
LastName string `json:"lname"` | ||
Email string `binding:"required,email"` | ||
} | ||
|
||
// UserStructLevelValidation contains custom struct level validations that don't always | ||
// make sense at the field validation level. For example, this function validates that either | ||
// FirstName or LastName exist; could have done that with a custom field validation but then | ||
// would have had to add it to both fields duplicating the logic + overhead, this way it's | ||
// only validated once. | ||
// | ||
// NOTE: you may ask why wouldn't not just do this outside of validator. Doing this way | ||
// hooks right into validator and you can combine with validation tags and still have a | ||
// common error output format. | ||
func UserStructLevelValidation(v *validator.Validate, structLevel *validator.StructLevel) { | ||
user := structLevel.CurrentStruct.Interface().(User) | ||
|
||
if len(user.FirstName) == 0 && len(user.LastName) == 0 { | ||
structLevel.ReportError( | ||
reflect.ValueOf(user.FirstName), "FirstName", "fname", "fnameorlname", | ||
) | ||
structLevel.ReportError( | ||
reflect.ValueOf(user.LastName), "LastName", "lname", "fnameorlname", | ||
) | ||
} | ||
|
||
// plus can to more, even with different tag than "fnameorlname" | ||
} | ||
|
||
func main() { | ||
route := gin.Default() | ||
|
||
if v, ok := binding.Validator.Engine().(*validator.Validate); ok { | ||
v.RegisterStructValidation(UserStructLevelValidation, User{}) | ||
} | ||
|
||
route.POST("/user", validateUser) | ||
route.Run(":8085") | ||
} | ||
|
||
func validateUser(c *gin.Context) { | ||
var u User | ||
if err := c.ShouldBindJSON(&u); err == nil { | ||
c.JSON(http.StatusOK, gin.H{"message": "User validation successful."}) | ||
} else { | ||
c.JSON(http.StatusBadRequest, gin.H{ | ||
"message": "User validation failed!", | ||
"error": err.Error(), | ||
}) | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
remove the command?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I can merge this PR after removing above command.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done.