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

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

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.

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

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

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}