Regex для Facebook-подобной проверки:
public static final String REGEX_EMAIL_VALIDATION = "^[\\w-\\+]+(\\.[\\w]+)*@[\\w-]+(\\.[\\w]+)*(\\.[a-zA-Z]{2,})$";
Dto для юнит-тестов (с Lombok):
@Data
@Accessors(chain = true)
@FieldDefaults(level = AccessLevel.PRIVATE)
public class UserCreateDto {
@NotNull
@Pattern(regexp = REGEX_EMAIL_VALIDATION)
@Size(min = 1, max = 254)
String email;
}
Действительные / недействительные письма ниже с юнит-тестами:
public class UserCreateValidationDtoTest {
private static final String[] VALID_EMAILS = new String[]{"email@yahoo.com", "email-100@yahoo.com",
"Email.100@yahoo.com", "email111@email.com", "email-100@email.net",
"email.100@email.com.au", "emAil@1.com", "email@gmail.com.com",
"email+100@gmail.com", "emAil-100@yahoo-test.com", "email_100@yahoo-test.ABC.CoM"};
private static final String[] INVALID_EMAILS = new String[]{"あいうえお@example.com", "email@111",
"email", "email@.com.my", "email123@gmail.", "email123@.com", "email123@.com.com",
".email@email.com", "email()*@gmAil.com", "eEmail()*@gmail.com", "email@%*.com", "email..2002@gmail.com",
"email.@gmail.com", "email@email@gmail.com", "email@gmail.com."};
private Validator validator;
@Before
public void setUp() throws Exception {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void emailValidationShouldBeValid() throws Exception {
Arrays.stream(VALID_EMAILS)
.forEach(email -> {
Set<ConstraintViolation<UserCreateDto>> violations = validateEmail(
new UserCreateDto().setEmail(email));
System.out.println("Email: " + email + ", violations: " + violations);
Assert.assertTrue(violations.isEmpty());
}
);
}
@Test
public void emailValidationShouldBeNotValid() throws Exception {
Arrays.stream(INVALID_EMAILS)
.forEach(email -> {
Set<ConstraintViolation<UserCreateDto>> violations = validateEmail(
new UserCreateDto().setEmail(email));
System.out.println("Email: " + email + ", violations: " + violations);
Assert.assertTrue(!violations.isEmpty());
}
);
}
private Set<ConstraintViolation<UserCreateDto>> validateEmail(UserCreateDto user) {
String emailFieldName = "email";
return validator.validateProperty(user, emailFieldName);
}
}