Creating Own Email List Validator
A quick code snippet to teach you how to create an email list validator, for when javax.validation just isn't enough.
Join the DZone community and get the full member experience.
Join For FreeValidating data is a must in the web development world. In most cases, javax.validation does the job out of the box. Just add some sort of annotations and that’s all. But there are some cases where there is a need to create your own validator. Below, you can find an example of how to do that.
The Goal
Validate a list of emails by using List<String> email with javax.validation and the Java 8 stream API.
Interface
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Constraint(validatedBy = {EmailListValidator.class})
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
public @interface EmailList {
String message() default "Invalid Email Address";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Validator Class With Regex Validation
import com.amazonaws.util.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;
import java.util.regex.Pattern;
/**
* Created by tj on 16.08.16.
* Email List validator
*/
public class EmailListValidator implements ConstraintValidator<EmailList,List<String>> {
final private Pattern emailPattern = Pattern.compile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$");
@Override
public void initialize(final EmailList constraintAnnotation) {
//for interface
}
@Override
public boolean isValid(final List<String> value, final ConstraintValidatorContext context) {
return !(value == null || value.isEmpty()) && value.stream().filter(e -> !StringUtils.isNullOrEmpty(e)).filter(e -> emailPattern.matcher(e).matches()).count() == value.size();
}
}
Test
/**
* Created by tj on 16.08.16.
* Email validator tests
*/
public class EmailListValidatorTest {
private static ValidatorFactory validatorFactory;
private static Validator validator;
@BeforeClass
public static void setup(){
validatorFactory = Validation.buildDefaultValidatorFactory();
validator = validatorFactory.getValidator();
}
@Test
public void validatorSingleCorrectEmailTest(){
final TestEntity emails = new TestEntity(Collections.singletonList("tjancz@gmail.com"));
final Set<ConstraintViolation<TestEntity>> violations = validator.validate(emails);
Assertions.assertThat(violations).hasSize(0);
}
private static class TestEntity {
@EmailList
private final List<String> emails;
public TestEntity(final List<String> emails) {
this.emails = emails;
}
}
}
Usage
public class SomeDTO {
@EmailList
private final List<String> emails;
// other content here
}
With these simple classes, you can validate a whole lists of elements.
Opinions expressed by DZone contributors are their own.
Trending
-
Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
-
Redefining DevOps: The Transformative Power of Containerization
-
Auto-Scaling Kinesis Data Streams Applications on Kubernetes
-
A Data-Driven Approach to Application Modernization
Comments