I have had an opportunity to play around with annotation and hibernate validation. Basically, hibernate has a few predefined annotations that you can use to annotate your getter methods. Later on, when in comes the user input, it will be validated based on the annotation type you use. For example -
@Length(max = 100)
@Email
public String getEmail() {
return email;
}
Here we are limiting the length of the String and also annotating it as an Email. The @Email annotation has a Validator class defined with @ValidatorClass annotation. The isValid() method of the respective validator gets called at runtime which then decided whether the input value is valid. You can find out more about it here.
Anyway, my problem in the above email field was, now we wanted to save multiple email addresses separated by comma. Since the default validator treats the whole value as one email address, it discards the input when there is a comma, obviously. Therefore, we needed a custom solution. After a bit of research and code digging, the final solution turned out to be very simple. But more importantly, elegant as well.
To implement custom validation in hibernate, all we need to do is define a new annotation and a corresponding validator. Lets first create the annotation.
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ValidatorClass(CustomEmailValidator.class)
public @interface CustomEmail {
String message() default "Email address not valid";
}
As you can see, our annotation is called CustomEmail (as opposed to Email in the first listing). We have written a new class named CustomEmailValidator and defined it here as our validator class. This class implements org.hibernate.validator.Validator which has a isValid method that will get called at runtime. All we needed to do was put our validation logic inside this method. Here is a part of the code
public class CustomEmailValidator implements Validator<CustomEmail>, Serializable {
public boolean isValid(Object value) {
// return true or false after validating value
}
}
Note, while implementing the Validator, we have to define the annotation name that this validator is linked with. Thats it! We just created implemented a new validation rule using hibernates validator framework.