Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Creating Own Email List Validator

DZone's Guide to

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.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

Validating 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.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
java 8 ,validation ,interface ,web developement ,annotations

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}