Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate all fields at once with HTML5 instead of one at a time

Is there a way to make HTML5 validate all fields at once instead of one at a time?

Using a couple of lines of JavaScript is OK but I don't really want to use an entire module for this.

I've searched quite a bit but couldn't find a clean solution for this.

Here is a sample form:

<html>
   <head>
      <title>Validation Test</title>
      <link href="css/style.css" rel="stylesheet">
   </head>
   <body>
      <form action="" id="myForm" method="post">
         <input id="name" name="name" required type="text">
         <input id="phone" name="phone" required type="text">
         <input type="submit" value="Submit">
      </form>
   </body>
</html>

Css file:

input:focus:required:invalid {
   border: 2px solid red !important;
}

The post suggested as a possible duplicate is for having multiple validation conditions for one field, I'm looking to validate / show all invalid fields at once.

like image 703
Mankind1023 Avatar asked Sep 29 '15 16:09

Mankind1023


Video Answer


1 Answers

If you don't want to use jQuery, that is fine. You can easily do this with vanilla js event handlers, and DOM selectors. I'm using jQuery for the sake of saving me time.

$('#myForm').on('submit', function() {
  var $inputs = $(this).find(':input'),
      isValid = true;

  $inputs.each(function() {
    if ($(this).val() == '') {
      isValid = false;
      $(this).addClass('error-control');
    } else {
      $(this).removeClass('error-control');
    }
  });

  return isValid  
});
like image 109
What have you tried Avatar answered Oct 26 '22 11:10

What have you tried