All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.opsbears.webcomponents.validator.FormalEmailValidator Maven / Gradle / Ivy

There is a newer version: 1.0.0-alpha14
Show newest version
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);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy