Let us say you have to validate a Collection of email values,public class Email {
@org.hibernate.validator.constraints.Email(message = "Email is not valid")
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;//More code here
Email emailClass = new Email();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
for (String e : emails) {
emailClass.setEmail(e.trim());
Set<ConstraintViolation<Email>> constraintViolations =validator.validate(emailClass);
if (!constraintViolations.isEmpty()) {
//Email is not valid. Perform the logic
}
}
I use Hibernate Validator implementation. Since I use Maven for build, the dependency is as below.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>