Explain Codes LogoExplain Codes Logo

Set custom HTML5 required field validation message

javascript
prompt-engineering
validation
html5
Alex KataevbyAlex Kataev·Sep 24, 2024
TLDR

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:

<input required oninvalid="this.setCustomValidity('Enter the necessary data please')" oninput="this.setCustomValidity('')">

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:

function InvalidInputHelper(inputField, options) { // Now we're talking. I will tell what's wrong (or right 😉) inputField.oninvalid = function(e) { let message = ""; if (!this.value) { message = options.emptyMessage; } else if (!this.validity.valid) { message = options.invalidMessage; } this.setCustomValidity(message); }; // Be nice, clear the message once they start typing, please! inputField.oninput = function(e) { this.setCustomValidity(''); }; }

In the example below, a custom message will pop up, depending on the state of the input field:

InvalidInputHelper(document.getElementById('myInput'), { emptyMessage: "Hey, you forgot something!", invalidMessage: "Whoops! That doesn't look right." });

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:

<input type="email" required oninvalid="this.setCustomValidity(this.value ? 'Emails have rules, check it! 😉' : 'Hey, we need your email!')" oninput="this.setCustomValidity('')" pattern="[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-z]{3}" >

Realtime feedback: Inputs that talk back instantly

For a more interactive experience, provide instantaneity feedback as soon as the user types in the field:

<input type="text" required oninvalid="this.setCustomValidity('Usernames have rules, buddy!')" oninput="this.setCustomValidity('')" pattern="^[a-zA-Z0-9_.-]*$" // This pattern here, Kinda like a BAR, only letters, numbers and underscores allowed! >

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:

<input type="text" required data-empty-message="Field is required" data-invalid-message="Invalid username" pattern="^[a-zA-Z0-9_.-]*$" >

Here's how to deal with different inputs in unified way:

document.querySelectorAll('input[required]').forEach(function(inputField) { inputField.oninvalid = function() { var message = this.value ? this.dataset.invalidMessage : this.dataset.emptyMessage; // Excuse me, User. Would you kindly... this.setCustomValidity(message); }; inputField.oninput = function() { // Alright, thank you! this.setCustomValidity(''); }; });

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.