vaadin / flow-components

Java counterpart of Vaadin Web Components
100 stars 66 forks source link

[EmailField] setPattern should not override the default email format but make it stricter #6561

Open vursen opened 1 month ago

vursen commented 1 month ago

Describe your motivation

Using setPattern currently overrides the default RFC 5322 email format entirely. Then, setting setPattern(null) does not restore the default regexp but removes it completely, turning EmailField into a regular text field.

This means that if you want, for example, to enforce a specific domain, you currently have to modify the standard email regexp and set it back using setPattern. This approach is inconvenient and prone to errors, which can accidentally allow invalid emails to slip through.

Describe the solution you'd like

Instead of overriding, setPattern should be used to add additional criteria on top of the default format, making it stricter. Similarly, setting setPattern(null) should simply remove the additional criteria while preserving the default format.

So, returning to the previous example where you want to enforce a specific domain, you should only need to provide a regular expression that will ensure that the email ends with the desired domain (e.g /.+@vaadin\.com$/), without having to deal with the complexity of the standard email format.

This will also require some changes to error message handling to distinguish between violations of the default and custom format. A new method, setBadInputErrorMessage(), would likely need to be introduced in the i18n object, while setPatternErrorMessage would need to be updated to only apply to violations of the custom format.

Describe alternatives you've considered

No response

Additional context

DX test finding from #4618

vursen commented 1 week ago

For the record, the proposed behavior aligns with that of the native <input type="email">:

Since inputs of type email validate against both the standard email address validation and the specified pattern, you can implement this easily.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email#pattern_validation