I'm trying to validate a bean using custom validator. But the validator needs info that is to be passed to it from the method where validate is invoked. Is there a way to do that?
I can't pass it in initialize as it is not available at the time of bean creation.
Bean to validate
class vehicle {
@VehicleNameValidator
String vehicleName;
}
Annotation
@Target({ElementType.FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = VehicleNameValidatorImpl.class)
@Documented
public @interface VehicleNameValidator {
String message() default "Invalid vehicle Name";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
custom validator
public class VehicleNameValidatorImpl implements ConstraintValidator<VehicleNameValidator, String[]> {
@Override
public boolean isValid(String vehicleName, ConstraintValidatorContext constraintValidatorContext) {
boolean isValid = logicmethod()//some logic here
return isValid;
}
}
Main method
public static void main(String[] args) {
String whatIwantToPass = runtimelogic(args);
vehicle veh1 = new vehicle();
Set<ConstraintViolation<vehicle>> constraintViolations =
validator.validate(veh1);
}
How to I pass variable "whatIwantToPass" from main method to VehicleNameValidatorImpl.