Normally the :invalid selector is evaluated instantly : The element will be styled immediately with :invalid for example if a value is required as soon as the page loads:
input:invalid {
border: 10px solid red;
}
<form>
<p> Go red only after I focused and blurred away </p>
<input required placeholder="you must type something" />
</form>
Would there be a workaround for this so that the evaluation happens only after the user interacts with the form? (typically, after the first focus / blur).
I understand this is standard browser implementation behavior so we’re likely looking for a workaround here.
Minimal JS is OK although I don’t want to do JS validation.
2
Answers
A possible solution would be to combine multiple pseudo-classes to achieve the result, as explained here.
Here’s an example (adapted from this Codepen) which shows the red border only if the value is invalid (in this case less than 3 characters in length).
Surely. Instead of setting the
required
attribute prematurely, you can mark items with something (arequired
class
in this case) and program the events you want to trigger the adding of therequired
attribute (blur
in this case):In the example above I’m adding the
required
attribute onblur
and removing it onfocus
, so it will not yell at users if they are removing the content while the item is being focused, but will be complaining whenever the item loses focus while not having a value.