Styling
It’s a common practice to indicate error states with styles, usually with red outlines, red error messages etc.
Input border
input-validity
is adding data-dirty
attribute after first submit attempt, but it’s recommended to use :invalid
CSS pseudo-class to add error styles when input is invalid.
Try to submit empty field and then add some value. Error styles will change to default automatically.
Styling error message
input-validity
doesn’t control rendering of error message DOM element - it only update it’s content.
Let’s add some styles to our error message.
As you can see our error message element is visible even without any actual message. It’s recommended to use :empty
CSS pseudo-class to handle such situations. No need for conditional rendering, adding or removing DOM elements, no templating.
Styling parent element
When you want to style parent element, for example indicate an error on the parent element such as card, fields group etc, it’s again recommended to just use CSS with :has()
. This will reduce need for client side javascript, conditional rendering or class manipulation.
TailwindCSS
input-validity
pairs nicely with TailwindCSS. Here’s above example styled with Tailwind