While basic HTML5 form validation already provides a useful way to validate user inputs, it is limited to basic validation techniques such as pattern matching, string length, or number ranges. Fortunately, there is a HTML5 API that allows you to set and trigger custom validation messages for form inputs, providing a more flexible and user-friendly native validation experience.
By utilizing setCustomValidity()
, you can define your own error message that will be displayed before submitting. When used in combination with reportValidity()
, it can further improve the user experience by triggering the invalid event and reporting the validation problem to the user at a certain point.
Below I'll explain the benefits of using setCustomValidity()
and reportValidity()
and provide an example on how you can use them to improve your form validation process.
Consider a scenario where you need to set up a form to capture a start and end date for a booking request. You need to ensure that the start date is smaller than or equal to the end date while the user is still picking dates. At this point, most people will start looking for libraries, which often add lots of unneeded code to your app, to take care of the validation logic.
This is where the setCustomValidity()
function comes in handy. You will just need to perform a check every time the input
event is called on your inputs and then set a custom error message if the check fails.
Let's take a look at the example:
As you can see in the example, you are also able to reset the custom error message by setting it to an empty string. At the end of the event handler you can see a call to the reportValidity()
method on the end date field. It triggers the invalid event and displays the error message, if any, to the user directly. If not called, the error message would only be displayed when you try to submit a parent form.
In addition to providing a flexible way to validate user inputs, using setCustomValidity()
together with reportValidity()
can also further improve the user experience by providing informative error messages and reducing the number of validation errors. By leveraging this native browser API you can simplify your form validation process while still providing a user-friendly validation experience, without using any library.
I hope you enjoyed this article and that I could help you! Show me what you build with this browser API!
If you are already using setCustomValidity
or have ideas for how to use it, feel free to comment below!
PS: I have attached another example below which shows how you could validate if a username is already taken before the user needs to submit their request. Try 'john_doe', 'jane_doe' or 'bob_smith.
Top comments (0)