如何在JavaScript中一次显示所有错误的循环?

时间:2021-06-23 02:04:14

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.

我目前正在进行JavaScript表单验证。对于个人而言,它正在应用所有错误,但我的任务是立即循环所有元素并立即显示错误。有没有解决方案。

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

当用户点击提交按钮时,任何人都可以帮助我如何循环显示所有错误吗?

3 个解决方案

#1


1  

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

首先,创建一个错误框。这可以使用简单的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!

其次,您不需要链接无限if语句。你可以使用梦幻般的精彩循环!

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

或者您可以使用jQuery和Validation插件。点击此处了解更多信息。一个简单的jQuery表单验证脚本

Happy coding!

#2


1  

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

首先,id在同一文档中应该是唯一的,因此您必须按类替换重复的ID,例如:

 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 :

然后只显示相关.error段落中输入的错误消息:

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>

#3


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

我没有对此进行测试,因此可能存在拼写错误

#1


1  

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

首先,创建一个错误框。这可以使用简单的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!

其次,您不需要链接无限if语句。你可以使用梦幻般的精彩循环!

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

或者您可以使用jQuery和Validation插件。点击此处了解更多信息。一个简单的jQuery表单验证脚本

Happy coding!

#2


1  

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

首先,id在同一文档中应该是唯一的,因此您必须按类替换重复的ID,例如:

 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 :

然后只显示相关.error段落中输入的错误消息:

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>

#3


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

我没有对此进行测试,因此可能存在拼写错误