validator icon indicating copy to clipboard operation
validator copied to clipboard

custom validation with params

Open elbek opened this issue 4 years ago • 7 comments

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 avatar Sep 27 '21 04:09 elbek

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

deankarn avatar Oct 23 '21 22:10 deankarn

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 avatar Feb 25 '22 14:02 Miguelklappes

@Miguelklappes do you mean dynamically passing in a value for validation with the field?

deankarn avatar Feb 26 '22 00:02 deankarn

@Miguelklappes do you mean dynamically passing in a value for validation with the field?

Hi Dean, yes.

Miguelklappes avatar Feb 26 '22 01:02 Miguelklappes

Is there any update? I am stuct with this and having to use package level global variable as a work around. Any help ?

aj619 avatar Oct 17 '22 23:10 aj619

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
}

saveriodesign avatar Jun 17 '23 18:06 saveriodesign

Is there solution for this? Is it possible to pass param (each time different) to the custom validation function?

lukalopusina avatar Mar 13 '24 16:03 lukalopusina