How to style HTML5 form validation messages
· Category: HTML & CSS
Short answer
Style HTML5 form validation using CSS pseudo-classes like :valid, :invalid, :required, and :user-invalid. For the validation message bubble itself, customization is limited in pure CSS, so many developers suppress the native tooltip and build a custom UI with JavaScript.
Details
Input elements expose states that you can target with CSS. For example, input:invalid { border-color: red; } changes the border when a field fails validation. The :user-invalid pseudo-class (supported in modern browsers) applies only after the user has interacted with the field, preventing aggressive red borders on page load.
Native validation bubbles can be suppressed with reportValidity() handling or by adding the novalidate attribute to the <form> and writing custom JavaScript logic. When building custom validation UI, you may want to read about how to avoid common JavaScript pitfalls and bugs to keep your validation code robust.
Tips
- Always pair client-side validation with server-side validation for security.
- Use
aria-invalid="true"andaria-describedbypointing to an error message to keep forms accessible. - If you need to check input values programmatically, see how to convert strings to numbers in JavaScript for handling numeric form fields safely.