1

I am currently working on JavaScript form validation. For individual it is applying all errors but my task is to loop all element at once and display error at once. Is there any solution?

<form action="" id="register" onsubmit="return validation()">
  Name<input type="text" id="name">
  <p id="error"></p>
  Email<input type="text" id="email">
  <p id="error"></p>
  Password<input type="text" id="password">
  <p id="error"></p>
  <input type="submit" name="submit" value="Submit">
</form>
<script>
  function validation() {
    if (document.getElementById('name').value=="") {
      document.getElementById("error").innerHTML="Please fill your name";
    }
    and so.. on..
  }
</script>

Can anyone help me how to for loop all errors to display at once when user click submit buttton?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
jvk
  • 2,133
  • 3
  • 19
  • 28

3 Answers3

2

First of all, create an error box. This can be done using a simply div.

<div id="error-box" style="color: red"></div>

Second, you don't need to chain infinite if statements. You can use the fantastic and wonderful for loop!

function validation() {
  var inputs = document.forms['myForm'].getElementsByTagName('input').length;

  for (i = 0; i <= inputs; i++) {
    if (document.forms['myForm'][i].value == "") {
        document.getElementById("error-box").innerHTML="Please fill " + document.forms['myForm'][i].name;
    }
  }
}

This will create an array of inputs and read one by one. If any field is empty, it will return an error into your error box. If not, execution continues.

Or you can use jQuery and Validation plugin. Check here for more info. A simple jQuery form validation script

Happy coding!

Community
  • 1
  • 1
Juanjo Salvador
  • 1,073
  • 1
  • 12
  • 33
  • Mr. Juanjo Salvador. I run your code on script. it is not looping it. Will please go through it. – jvk Aug 02 '16 at 09:37
  • Hi Your code is fine there are few things are not working fine. Will you please check it once and please do this working example in fiddle. It will help me alot. Thank you – jvk Nov 23 '16 at 08:24
  • Hi The code you written in jsfiddle.net. unable to open. Will you please check it once. I am getting 404 error. We're truly sorry, but there is no such page. Thanks Juanjo Salvador. you are helping me a lot. – jvk Nov 28 '16 at 10:54
  • jsFiddle is going wrong... Check this link https://jsfiddle.net/jsalvador/21abrxg7/ – Juanjo Salvador Nov 29 '16 at 14:36
  • the above code is not working for my html code , please share the related html code. – Santhi seeram Jan 10 '20 at 11:55
2

First the id should be unique in same document so you have to replace duplicate ones by classes, e.g :

 Name<input type="text" id="name">
 <p class="error"></p>

 Email<input type="text" id="email">
 <p class="error"></p>

 Password<input type="text" id="password">
 <p class="error"></p>

Then just show the error message of the input in the related .error paragraph :

function validation() {
   if ($('#name').val()==="") {
       $('#name').next(".error").html("Please fill your name");
   }
}

Hope this helps.

$('#register').on('submit', function(){
  var submit = true;

  if ($('#country').val()==='-1'){
    $('#country').next(".error").html("Please fill your country");
    submit = false;
  }else
    $('#country').next(".error").html("");

  if ($('#name').val()===""){
    $('#name').next(".error").html("Please fill your name");
    submit = false;
  }else
    $('#name').next(".error").html("");


  if ($('#email').val()===""){
    $('#email').next(".error").html("Please fill your email");
    submit = false;
  }else
    $('#email').next(".error").html("");

  if ($('#password').val()===""){
    $('#password').next(".error").html("Please fill your password");
    submit = false;
  }else
    $('#password').next(".error").html("");

  if ($('[name="check"]:checked').length===0){
    $('[name="check"]:last').next(".error").html("Please check one at least");
    submit = false;
  }else
    $('[name="check"]').next(".error").html("");

  return submit;
})
.error{
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" name="register" id="register">
  Country 
  <select name="country" id="country">
    <option value="-1">Select country please</option> 
    <option value="usa">USA</option> 
    <option value="austriala">Austriala</option> 
    <option value="india">India</option>
  </select>
  <p class="error"></p>

  Name <input type="text" id="name">
  <p class="error"></p>

  Email <input type="text" id="email">
  <p class="error"></p>

  Password <input type="text" id="password">
  <p class="error"></p>

  Checkboxes 
  <br>
  <input type="checkbox" name="check" value="check_1">check 1
  <br>
  <input type="checkbox" name="check" value="check_2">check 2
  <br>
  <input type="checkbox" name="check" value="check_3">check 3
  <p class="error"></p>

  <input type="submit" name="submit" value="Submit">
</form>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • Mr. Zakaria Acharki. Can please tell we are using next in code – jvk Aug 02 '16 at 09:46
  • Hi, `next()` used to get the next `p.error` after every input, so `$('#name').next(".error")` will filter just the error paragraph that come directly after the `#name` input so when we will use `.text()` to append text we will not affect other inputs errors. – Zakaria Acharki Aug 02 '16 at 10:05
  • The code you have written it is not working for checkbox and radio input type. Will you check it. – jvk Aug 05 '16 at 07:04
  • Hi, sure it will not work since it have a different logic, check my update for the checkboxes... for the radios what you want to check ? since one radio input at least should be selected by default.. – Zakaria Acharki Aug 05 '16 at 08:15
  • Ok. Thank you for you time with me. But I have tried this way if ($('input:checkbox').is(':checked')) { } else { $('input:checkbox').next(".error").html("Please submit your terms and conditions"); submit = false; }, will you write some code on how to select option to select validation before form submit. – jvk Aug 05 '16 at 08:21
  • Ur welcome, not sure what you mean by _how to select option to select validation before form submit_, try to update the OP with description.. – Zakaria Acharki Aug 05 '16 at 09:11
  • Ackarki. Thank you for helping me. My question If user does not select any value . I want to display error like please select your country before form submited. One more question you checkbox:last. does it manitory – jvk Aug 05 '16 at 09:17
  • Hi, check the select example added to the answer.. `checkbox:last` is mandatory if you have several checkboxes if you have just one it's not. – Zakaria Acharki Aug 05 '16 at 09:48
  • thank so much sit ,this is very useful but I need the same jquery code in to javascript code, please help me. – Santhi seeram Jan 14 '20 at 03:29
0

Hmm. How about a native way? :)

function select( cssSelector ){ return document.querySleectorAll( cssSelector ) };

var inputs = select( '#register input' );  // selects array of all child inputs

//setup all validations within an object
var validations = {
   name: function( nameText ){
      //shorthand if-statements, expand if you need to
      return ( nameText === "" ) ? "error, cannot be empty" : "ok";
   },
   password: function( passText ){
      return ( passText.length < 8 )? "too short" : "ok";
   }
};

//iterate over all inputs
for( var elem in inputs ){
   if( validations[ inputs[ elem ].id ] ){ // if validation rule exists..
      console.log( "input nr " + elem + "tested\n" +
      "id = " + inputs[ elem ].id + "\n" + 
      "outcome: " + validations[ inputs[ elem ] ] );
   }
}

I have not tested this so there might be typos

25r43q
  • 613
  • 4
  • 16