govalidator
govalidator copied to clipboard
Support for custom validators with parameters
I am trying to use govalidator in one of my projects but struggling to implement validator for password confirmation:
type UserForm struct {
Email string `valid:"required,email"`
Password string `valid:"required,confirmation(PasswordConfirmation)"`
PasswordConfirmation string `valid:"required"`
}
It looks like custom validators can not accept any parameters at the moment.
I understand that I can use a workaround by hard-coding PasswordConfirmation
field name in my custom validator, but I would like it to be re-usable.
I was wondering if there will be any interest in implementing this feature? If yes, then I can implement it and send a PR.
+1, would be great to support custom ParamValidator
@andreychernih it would be great!
+1
+1
I know this one is pretty old, and you guys probably know how to do this, but just in case someone else like me stumbles upon this issue - I found a way to do this:
type User struct {
CompanyID string `valid:"exists(a|b)"`
}
var existingValidatorRegex = regexp.MustCompile("^exists\\((.+)\\|(.+)\\)$")
func InitValidators() {
ParamTagMap["exists"] = ParamValidator(existingValidator)
ParamTagRegexMap["exists"] = existingValidatorRegex
}
func existingValidator(val string, params ...string) bool {
fmt.Println(val, params)
return params[0] == "a" && params[1] == "b"
}
I'm not sure if the official API supports this but it seems to be working. Please let me know if I'm wrong.
@naoric This is how we've been forced to do it too. It seems to work, but it'd be nicer to have a neater way of doing this.
You can create something like this. I've implemented it in my code and it works.
Here is the simple example with 1 parameter (you can add more parameters as you want)
// Add your own struct validation tags with parameter
govalidator.ParamTagMap["animal"] = govalidator.ParamValidator(func(str string, params ...string) bool {
species := params[0]
return str == species
})
//register the regex for validate
govalidator.ParamTagRegexMap["animal"] = regexp.MustCompile("^animal\\((\\w+)\\)$")
If you validate this struct, the validator will return true
type Post struct {
Test string `valid:"animal(dog)"`
}
If you validate this struct, the validator will return false
type Post struct {
Test string `valid:"animal(cat)"`
}
Hello guys! I forked this package cause owner disappeared. Hope, he will be back, but it would be easier to merge these changes back if he is back Link to my repo: create issue there and we'll discuss it.