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;
0 comments:
Post a Comment