Set custom HTML5 required field validation message
To deliver tailored validation messages, use the setCustomValidity
method and the required
attribute alongside oninvalid
and oninput
event attributes. The resulting code looks something like this:
Now, if an input field fails the validation test, the custom message is displayed. It's reset whenever the user amends their input.
Implementing multiple validation messages
Here's how to customize validation messages for different scenarios using an InvalidInputHelper
function:
In the example below, a custom message will pop up, depending on the state of the input field:
Differentiating the type of validation error
By combining pattern
attribute and the setCustomValidity
function, you can display a distinct message depending on whether a field is empty or contains an invalid pattern:
Realtime feedback: Inputs that talk back instantly
For a more interactive experience, provide instantaneity feedback as soon as the user types in the field:
Custom data attributes: One size doesn't fit all
Not all inputs need the same default message. Use custom data attributes to keep your form flexible and avoid repeating yourself:
Here's how to deal with different inputs in unified way:
Compatibility: Browsers are picky, you know
Our "chaty validation" technique is user-friendly and is compatible across all major browsers including Chrome, IE, Edge, Firefox, and Opera.
Incorporating accessibility
A comprehensive validation approach ensures that the application is accessible to all users. Remember to use ARIA labels and descriptive messages, and carry out testing with screen readers to guarantee that the messages are delivered effectively.
Don't forget the server
Client-side validation uplifts user experience, but server-side validation is a must-have for ensuring data integrity and bolstering security. The former compliments, but should never replace, the latter.
Was this article helpful?