I'm building a form and I want to use the :invalid
selector to give the "required" input fields a red border if the user presses submit without filling them, but using this makes them appear highlighted right when the page loads. It seems unfriendly to give this kind of warning to the user before even giving him the chance to fill them at least once.
Is there a way that these fields appear highlighted only after trying to submit the form, said in another way, is there a way to run the validation only after clicking submit (or at least losing focus on the required input fields?)
Another way is to add a
hide-hints
class to the inputs with JavaScript on load. When a user modifies a field you remove the class.In your CSS you then apply styling to
input:not(.hide-hints):invalid
. This means the error styling will be shown for users without JavaScript as well.Very simple just use #ID:invalid:focus
This only does the validation when focused on and not on page load
No there is nothing out of the box.
Mozilla has its own pseudoclass for something very similiar called ':-moz-ui-invalid'. If you want to achieve something like this, you have to use the constraint validation DOM-API:
You can also use webshims lib polyfill, which will not only polyfill incapable browsers, but also adds something similiar like -moz-ui-invalid to all browser (.form-ui-invalid).
I used this approach for a project of mine, so the invalid fields would be highlighted only after submit:
HTML:
CSS:
JS (jQuery):
Old question, but for people that might might find it useful: I made a little script that adds a class to a form when it's attempted to be submitted, so that you can style forms that have and haven't been attempted to be submitted differently:
Now forms that are attempted to be submitted will get a class
_submit-attempted
, so you can only give these fields a red box shadow:You can achieve this by chaining pseudo-classes:
that way the input field will just show invalid styles only when that input field required and focused.
Here is a helpful article: https://alistapart.com/article/forward-thinking-form-validation/
Another stack overflow thread on this: https://stackoverflow.com/a/7921385/11102617