com.opsbears.webcomponents.validator.FormalEmailValidator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of validator Show documentation
Show all versions of validator Show documentation
Utilities for basic validations.
package com.opsbears.webcomponents.validator;
import javax.annotation.Nonnull;
import java.util.regex.Pattern;
public class FormalEmailValidator implements EmailValidator {
private static Pattern localPartPattern;
private boolean allowEmpty = false;
private DomainNameValidator domainNameValidator;
public FormalEmailValidator() {
this.domainNameValidator = new FormalDomainNameValidator();
}
public FormalEmailValidator(@Nonnull DomainNameValidator domainNameValidator) {
this.domainNameValidator = domainNameValidator;
}
public FormalEmailValidator(boolean allowEmpty) {
this.allowEmpty = allowEmpty;
domainNameValidator = new FormalDomainNameValidator();
}
public FormalEmailValidator(boolean allowEmpty, @Nonnull DomainNameValidator domainNameValidator) {
this.allowEmpty = allowEmpty;
this.domainNameValidator = domainNameValidator;
}
private static Pattern getLocalPartPattern() {
if (localPartPattern == null) {
localPartPattern = Pattern.compile("\\A[a-zA-Z0-9\\-_+.\\x{007F}-\\x{FFFF}]+\\z", Pattern.UNICODE_CASE);
}
return localPartPattern;
}
@Nonnull
@Override
public String getUniqueKey() {
return "email-format";
}
@Override
public boolean isValidString(@Nonnull String value) {
if (allowEmpty && value.equals("")) {
return true;
}
if (value.contains("\n")) {
return false;
}
if (!value.contains("@")) {
return false;
}
String[] parts = value.split("@", 2);
String localPart = parts[0];
String domain = parts[1];
return getLocalPartPattern().matcher(localPart).matches() && domainNameValidator.isValidString(domain);
}
}