Thursday, 22 August 2013

Hibernate Custom validator to validate Multiple email ids

In my current project, i need to validate email ids where user will be enter more email id in one text area with semicolon as separator. Before storing into DB, i need to check whether all the email ids are valid one. So i decided to create custom Hibernate validator constraint. For more examples and understanding, please check here

package com.hibernate;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = ValidateEmailValidator.class)
@Documented
public @interface ValidateEmails {

String message() default "{default message}";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};

}



package com.hibernate;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class ValidateEmailValidator implements
ConstraintValidator<ValidateEmails, String> {

String emailPattern = ".+@.+\\.[a-z]+";
private final Pattern EMAIL_PATTERN = Pattern.compile(emailPattern);

@Override
public void initialize(ValidateEmails arg0) {

}

@Override
public boolean isValid(String value,
ConstraintValidatorContext constraintContext) {
if (value == null) {
return true;
}
boolean isValid = true;
String delimiter = ";";
String[] temp;
temp = value.split(delimiter);
for (int i = 0; i < temp.length; i++) {
if (validateEmail(temp[i]) == false) {
return false;
}
}
return isValid;
}

private boolean validateEmail(String email) {

return validatePattern(email, EMAIL_PATTERN);
}

private boolean validatePattern(String toBeValidated, Pattern pattern) {
if (toBeValidated == null)
return false;
Matcher m = pattern.matcher(toBeValidated);
return m.matches();
}
}


Example Usage:

@ValidateEmails(message = "Some email ids are invalid for Send result to email.")
private String resultEmails;

No comments:

Post a Comment

CSS Classes and Styles