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?

2
  • 6
    id should be unique in same document... do you have any validation code? Commented Aug 2, 2016 at 8:26
  • @zakaria Acharki. Please check code once. Commented Aug 2, 2016 at 8:34

3 Answers 3

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!

Sign up to request clarification or add additional context in comments.

5 Comments

Mr. Juanjo Salvador. I run your code on script. it is not looping it. Will please go through it.
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
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.
jsFiddle is going wrong... Check this link jsfiddle.net/jsalvador/21abrxg7
the above code is not working for my html code , please share the related html code.
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>

9 Comments

Mr. Zakaria Acharki. Can please tell we are using next in code
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.
The code you have written it is not working for checkbox and radio input type. Will you check it.
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..
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.
|
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.