custom validation with params
I am trying to register a custom validator with parameter so I can use the same validator with different params in different struct fields.
I have a status field type which takes 3 values, pending, active, inactive and I would like to write a validator to check if values are right
Code sample, to showcase or reproduce:
// field in a struct
Status common.Status `validate:"required,status|active|inactive"` // this field can only take two values for status
// this is how I register:
validate.RegisterValidation("status", StatusValidator)
I get an error saying Undefined validation function 'active' on field 'Status'. active and inactive are params used withing status validator. How can I accomplish this. It seems similar to hexcolor validator.
@elbek it appears that you are missing the = sign and it should be status=active|inactive can you try that and let me know if that solves your issue?
Regarding this, I still can't find a way to register custom validation with params, not just passing an string in the reflect struct, but a real value.
@Miguelklappes do you mean dynamically passing in a value for validation with the field?
@Miguelklappes do you mean dynamically passing in a value for validation with the field?
Hi Dean, yes.
Is there any update? I am stuct with this and having to use package level global variable as a work around. Any help ?
For your situation I'd probably use a more generic name than "status", like "in" which is not one of the baked-in validations at this time. The package will interpret pipes, commas, and semicolons as rule separators, so I'm using the middle dot character as the enum separator for my own "in" rule.
func inRule(data validator.FieldLevel) bool {
target := data.Field().String()
// allow empty, should use with "required" if so
if target == "" {
return true
}
// middle dot (option-shift-9) because the pipe, comma and semicolon
// seem to separate discrete validation rules
list := strings.Split(data.Param(), "·")
i := sort.SearchStrings(list, target)
return i < len(list) && list[i] == target
}
Is there solution for this? Is it possible to pass param (each time different) to the custom validation function?