TextField validation with Binder - not required value

Hi,
I have simple email textfield :

TextField emailTF = new TextField();
emailTF.setRequired(false);
buyerBinder.forField(emailTF)
.withValidator(new EmailValidator(“Not valid email address”))
.bind(PartnerAddressStruct::getEmail, PartnerAddressStruct::setEmail);

Value of this field should be empty or valid email address. But EmailValidator is always execute and I also get error for empty values. How can I set binder to allow empty values? Thank you.
Regards,
Matic

Hi Matic,
please notice that EmailValidator is very simple class extending RegexpValidator. What I suggest is to create your own class i.e. EmptyOrEmailValidator extending RegexpValidator. The only difference between your class and the original EmailValidator should be the Regex pattern that you define. So instead of:

    private static final String PATTERN = "^" + "([a-zA-Z0-9_\\.\\-+]
)+" // local
            + "@" + "[a-zA-Z0-9-.]
+" // domain
            + "\\." + "[a-zA-Z0-9-]
{2,}" // tld
            + "$";

You should have (just enhance the first element with “$|” in order to allow the empty strings):

    private static final String PATTERN = "^$|" + "([a-zA-Z0-9_\\.\\-+]
)+" // local
            + "@" + "[a-zA-Z0-9-.]
+" // domain
            + "\\." + "[a-zA-Z0-9-]
{2,}" // tld
            + "$";

Should work but please verify it and - as always - write tests to your code :slight_smile:

Hi,

Thank you for solution. My implementation was by using custom validation method. But I think it should exist some standard Binder solution for this problem. For example - if you mark Field as required = false, then it is not needed that validator is even call.

TextField emailTF = new TextField();
emailTF.setRequired(false);
buyerBinder.forField(emailTF)
.withValidator(v -> emailValidation(v), "Not valid email address")
.bind(PartnerAddressStruct::getEmail, PartnerAddressStruct::setEmail);
	boolean emailValidation(String value) {
    	if (StringUtils.isBlank(value)) {
    		return true;
		}

		org.apache.commons.validator.EmailValidator validator = org.apache.commons.validator.EmailValidator.getInstance();
		return validator.isValid(value);
	}

Hi =)
try binder.(blabla).withNullRepresentation(“”).withValidator…

i built a solution to this.

see the class conditionalvalidator.

it’s well down the page.

https://github.com/vaadin/framework/issues/10709