In previous articles I’ve shown how to set custom error messages for HTML5 forms with CSS and JavaScript. Recently Estelle Weyl demonstrated a method that seems to have gone largely unremarked in browser and spec documentation: form validation customization by using the title
attribute.
There is just one requirement: the input must have a pattern
(i.e. a regular expression) that entered data can be tested against. That often implies that the field will also be required. For example:
<form>
<label for="name">Your name</label>
<input type="text" id="name" pattern="^([ \u00c0-\u01ffa-zA-Z'\-]){2,50}$" title="Please enter only letters (hyphens and spaces may be included)" required>
<input type="submit" value="Test">
</form>
This form asks for the name field to be filled out with at least two characters: the Unicode range in the regular expression ensures that accented “European” characters will also be accepted in the name (for example, Jérôme L'merchanté).
The title
attribute value contains the custom error message that is shown to the user: try entering a number into the field and pressing the submit
button.
Where Does This Work?
As far as my testing has determined, this technique works in the latest versions of all modern browsers – that is, every one that supports client-side HTML5 patternMismatch – with the odd and singular exception of desktop and mobile Safari.
Detecting support for this particular feature may be a little tricky; in the short term, you could fallback to user agent detection in a polyfill:
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('safari') != -1 && ua.indexOf('chrome') == -1) {
// polyfill for Safari
}
I’ll have more on the possibilities for this polyfill in an article here on the blog, to be published in the very near future.
How Can I Customize The Error Message Bubble Itself?
Unfortunately, at this time, you can’t. Webkit/Blink recently removed the pseudo-selectors for customizing the error message bubble, and Firefox has never supported doing so. If you want your own completely custom message and appearance I suggest you use the JavaScript or CSS techniques I mentioned earlier.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.