Form Error Messages Styles
Contents |
written and spoken about HTML5 form validation over the last few years, and one of the most common questions I get is about bubbles. By bubbles webkit-validation-bubble-message I mean the UI controls browsers display validation errors in. Below you html5 error message style can see Chrome's, Firefox's, and IE's implementations: For whatever reason, we developers (or more likely our designer colleagues) html5 form validation custom message have a deep-seated desire to style these things. But unfortunately we can't, as zero browsers provide styling hooks that target these bubbles. Chrome used to provide a series of vendor prefixed html5 validation message css pseudo-elements (::-webkit-validation-bubble-*), but they were removed in Chrome 28. So what's a developer to do? Well, although browsers don't allow you to customize their bubbles, the constraint validation spec does allow you to suppress the browser's bubble UI and build your own. The rest of the article shows you how to do just that. Warning: Don’t go down the path of
Validation-bubble-message Css
building a bubble replacement lightly. With the default bubbles you get some pretty complex functionality for free, such as positioning and accessibility. With custom bubbles you have to address those concerns yourself (or use a library that does). Suppressing the Default Bubbles The first step to building a custom UI is suppressing the native bubbles. You do that by listening to each form control's invalid event and preventing its default behavior. For example, the following form uses no validation bubbles because of the event.preventDefault() call in the invalid event handler.
script document.querySelector( "input" ).addEventListener( "invalid", function( event ) { event.preventDefault(); }); The invalid event does not bubble (no pun intended), so if you want to prevent the validation bubbles on multiple elements you must attach a capture-phase listener. If you're confused on the difference between the bubbling and capturing phases of DOM events, check out this MDN article for a pretty good explanation. The following code prevents bubbles on both inputs with a single invalid event listener on the parent