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?)
HTML5 validation kicks in when the form is submitted (user clicks the Submit button). When this happens, the browsers starts going through its list of required inputs and prompts when the input is missing on the required inputs.
The value must be greater than or equal to the value. There must be a value (if set). Unless the step is set to the any literal, the value must be min + an integral multiple of the step. The number of characters (code points) must not be less than the value of the attribute, if non-empty.
Required Attribute Validation doesn't Work with Unclosed Input Tags. If the field misses the closing tag at the end then most probably the validation won't work. So always close the tags in either way.
Using HTML5, we can create a form with built in validation (i.e. no javascript required). Earlier, we were using JAVASCRIPT to control form validation.
I used this approach for a project of mine, so the invalid fields would be highlighted only after submit:
HTML:
<form> <input type="email" required placeholder="Email Address"> <input type="password" required placeholder="Password"> <input type="submit" value="Sign in"> </form>
CSS:
input.required:invalid { color: red; }
JS (jQuery):
$('[type="submit"]').on('click', function () { // this adds 'required' class to all the required inputs under the same <form> as the submit button $(this) .closest('form') .find('[required]') .addClass('required'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With