Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation in HTML5. :invalid classe after submit

Tags:

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?)

like image 418
Enrique Moreno Tent Avatar asked Sep 27 '11 22:09

Enrique Moreno Tent


People also ask

How does HTML5 validation work?

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.

Which are the correct input restrictions used for validation purpose in HTML5?

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.

Why validation is not working in HTML?

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.

Does HTML5 have form validation?

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.


Video Answer


1 Answers

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'); }); 
like image 153
Cezar D. Avatar answered Oct 05 '22 10:10

Cezar D.