Flow: EmailValidator doesn't pass on an empty string

Created on 26 Mar 2020  路  7Comments  路  Source: vaadin/flow

Vaadin 14.1.19. I have the following code:

binder.forField(new TextField()).withValidator(new EmailValidator()).bind("field");

However, the validator marks an empty TextField as invalid, effectively disabling the possibility to have an optional email.

Certainly I can hook a converter before the validator which converts empty string to null and vice versa (it's required anyway because of TextField rejecting nulls), but I wonder whether EmailValidator should pass blank strings?

binder enhancement

Most helpful comment

I suggest to overload EmailValidator CTOR with a boolean value which says whether an empty value should be accepted or not.
That will keep binary compatibility and won't require introducing a new class.

All 7 comments

I would guess this is the same for if you use RegexpValidator?

I think so. However the RegexpValidator is much more versatile and might be (mis)used to match non-blank strings, so I'm not sure whether RegexpValidator should pass for blank strings. Maybe an optional constructor parameter?

Feels like that. Else the email regex should be able to accept an empty value.

Any workaround for this?

new EmailValidator() {
protected boolean isValid(String value) {
if ("".equals(value)) return true;
return super.isValid(value);
}
}

Would be easy to contribute an OptionalEmailValidator or such which also accepts "". But we've had CompositeValidator earlier on https://vaadin.com/api/framework/7.7.17/com/vaadin/data/validator/CompositeValidator.html, I guess it should be just easy to chain the existing validators.

I suggest to overload EmailValidator CTOR with a boolean value which says whether an empty value should be accepted or not.
That will keep binary compatibility and won't require introducing a new class.

Was this page helpful?
0 / 5 - 0 ratings