Form Validation – part 6 (Custom Form Validation Annotation with Parameters)

Custom Form Validation Annotation With Parameters

Suppose we have a requirement where we have to create Custom Form Validation Annotation that accepts parameters  and then used this annotation like any other build in annotation in your application

For this we will continue with our previous example and edit it accordingly

So for the previously created custom form validation for the hobby field we will let developer to pass parameters like we have option for @Size annotation where we provide the min and max values as parameters.

Currently in our HobbyValidator.java file we have the hardcoded values for list of hobbies as below;

public class HobbyValidator implements ConstraintValidator<IsValidHobby,String> {

@Override
public void initialize(IsValidHobby isValidHobby) {

}

@Override
public boolean isValid(String studentHobby, ConstraintValidatorContext ctx) {

if(studentHobby == null){
return false;
}

if(studentHobby.matches(“Skating|Music|Reading“)){
return true;

}
else{
return false;
}
}

}

Something to always Remember :

A Custom Annotation class always make call to isValid() function of its corresponding validation class ,but before making call to isValid() function its make a call to initialize() function

Before performing the actual validation the Actual validation class(HobbyValidator.java) should get the list of hobbies entered by the Developer in Student.java

@Size(min=3, max=25)@IsValidHobby(listOfValidHobbies=”Skating|Music|Reading”)
private String studentHobby;

customannotationparam11

so we can get those values in HobbyValidator.java as below as initialize function will get called prior validation the inputs

public void initialize(IsValidHobby isValidHobby) {
isValidHobby.listOfValidHobbies();

}

next we will also create a String variable listOfValidHobbies and assign the list of hobbies set by Developer  as

private String listOfValidHobbies;
@Override
public void initialize(IsValidHobby isValidHobby) {
this.listOfValidHobbies =isValidHobby.listOfValidHobbies();

}

Then later pass this variable listOfValidHobbies to validate

if(studentHobby.matches(listOfValidHobbies)){
return true;

}

After all this in class Student.java
@Size(min=3, max=25)@IsValidHobby(listOfValidHobbies=”Skating|Music|Reading”)
private String studentHobby;

listOfValidHobbies becomes a mandatory parameter and now if we dont provide it then it start showing error,

customannotationparam1

so how to make this an optional parameter by providing some default values to the annotation.

This can be achieved by adding a default values in isValidHobby.java as below:

customannotationparam2


   

Comments are closed