Beyond that, there is a bunch of other ways that you can add constraints to your input. Precisely, there are three ways to do it: The last one is the

HTML Form Validation is heavily underused

submited by
Style Pass
2024-10-28 21:30:02

Beyond that, there is a bunch of other ways that you can add constraints to your input. Precisely, there are three ways to do it:

The last one is the most powerful as it allows to create arbitrary validation logic and handle complex cases. Do you notice how it differs from the first two techniques? The first two are defined with attributes, but setCustomValidity is a method.

Here’s a great write-up that explains the differences between DOM attributes and properties: https://jakearchibald.com/2024/attributes-vs-properties/

The fact that setCustomValidity API is exposed only as a method and doesn’t have an attribute equivalent leads to some terrible ergonomics. I’ll show you with an example.

That’s pretty much it! Now let’s apply this knowledge. Let’s say we want to implement an equivalent of the required attribute. That means that an empty input must be prevent the form from being submitted.

It may seem to work, but there’s just one important edge case: the input is in a valid state initially. If you reset the component and press the “submit” button, the form submission will go through. But surely, before we ever touch the input, it is empty, and therefore must be invalid. But we only ever do something when the input value changes.

Leave a Comment