使用FOR LOOP进行Javascript表单验证

时间:2017-11-09 10:25:41

标签: javascript php jquery html validation

我需要一些JavaScript帮助,使用JavaScript中的 for 进行表单验证。

我有一个包含5个用户名和密码字段的表单,需要先使用JavaScript验证表单才能提交给数据库。

您可以看到我需要的代码和结果here in this JsFiddle

这是我认为的代码:

<form action="insertMember" method="post" name="fmember" onsubmit="return validateMember()">
    <div class="form-group">
       <label>Shop</label>
       <select>
          <option value="">Choose The Host</option>
          <option value="1">Shop 1</option>
          <option value="2">Shop 2</option>
       </select>
    </div>
    <?php 
    $max = 5;
    for($i=1; $i<=$max; $i++) { ?>
       <span class="error<?php echo $i; ?>" class="label label-danger"></span>
       <label>Username <?php echo $i; ?></label>
       <input type="text" name="user[<?php echo $i; ?>]">
       <label>Password <?php echo $i; ?></label>
       <input type="password" name="pass[<?php pass $i; ?>]">
       <span class="errorp<?php echo $i; ?>" class="label label-danger"></span>
    <?php } ?>
</form>

这是我的Javascript代码(仍然是错误):

// How to validate input using FOR LOOP ?
// $max or max can be changes to 10 or more.
function validateMember() {
// I got an error from here.
        var max = 3;
    var member = [];
    var password = [];
    for(var i=1; i<=max; i++) {
        var member = document.forms.fmember.user[i].value;
        var password = document.forms.fmember.pass[i].value;
      // Validate only username 1 must be filled or return error message
      if(i == 1) {
         if(member[i] == '') {
             document.getElementByID('error'+i).innerHTML = 'Username Must be Filled !';
             return !1;
         }
         else if (password[i] == '') {
                 document.getElementByID('errorp'+i).innerHTML = 'Password Must be Filled !';
             return !1;
         }
         else {
             return !0;
         }
      }
      else {
      // Validate if username 2 until MAX are filled must have min length = 2
         if(member[i] != '') {
               if(member[i].length < 2) {
                         document.getElementByID('error'+i).innerHTML = 'Username Must Have Minimum 2 Characters';
                       return !1;
                 }
             else {
                            return !0;
                }
         }
      }
    }
}

2 个答案:

答案 0 :(得分:1)

我不确定代码是如何尝试使用max变量的,但是这应该可以帮助您:

$.each( $( "#input input" ), function( key, element ) {

        if( !$(element).val() ) {

            $( "#error" + key ).text( "Input " + $( element ).attr( "name" ) + " is required" );

            return false;

    }

});

简单地用这个替换旧的JS。

答案 1 :(得分:1)

这里有多个问题:

  1. 输入元素的 name 属性值具有数组语法

    <input type="text" name="user[1]">
    

    但是当通过Javascript访问它们时,document.forms.fmember在键用户中不包含数组 - 每个元素都有一个唯一键。尝试在您的控制台中运行此操作:Object.keys(document.forms.fmember.elements)。你应该看到如下的数组:

    ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "shop", "user[1]", "pass[1]", "user[2]", "pass[2]", "user[3]", "pass[3]", "user[4]", "pass[4]", "user[5]", "pass[5]"]
    

    所以更新这一行:

     var member = document.forms.fmember.user[i].value;
    

    要:

     var member = document.forms.fmember["user["+i+"]"].value;
    

    password变量的相同内容:

    var password = document.forms.fmember["pass["+i+"]"].value;
    
  2. 包含文本输入值的变量(即memberpassword)的值为string类型,因此要检查空字符串,只需使用{{1而不是if(member == '') { ...

  3. 请参阅下面的操作中的这些更改(或updated plunker)。

    &#13;
    &#13;
    if(member[i] == '') {
    &#13;
    $('#shop').on('change',function() {
    		$('#input').fadeIn(1000);
    		if ($('#shop').val() == '') {
        		$('#input').fadeOut(500);
         }
    });
    
    // The question is HERE
    // How to validate input using FOR LOOP ?
    // Because the $max or max can be changed to 10 or more.
    function validateMember() {
    // I got an error from here.
    		var max = 3;
        var member = [];
        var password = [];
        for(i=1; i<=max; i++) {
        		var member = document.forms.fmember["user["+i+"]"].value;
            var password = document.forms.fmember["pass["+i+"]"].value;
          // Validate only username 1 must be filled or return error message
          if(i == 1) {
             if(member== '') {
          	     document.getElementById('error'+i).innerHTML = 'Username Must be Filled !';
          	     return !1;
             }
             else if (password == '') {
          			 document.getElementById('errorp'+i).innerHTML = 'Password Must be Filled !';
              	 return !1;
             }
             else {
                 return !0;
             }
          }
          else {
          // Validate if username 2 until MAX are filled must have min length = 2
             if(member != '') {
          		   if(member.length < 2) {
           				 	 document.getElementByID('error'+i).innerHTML = 'Username Must Have Minimum 2 Characters';
          				   return !1;
            		 }
                 else {
          						return !0;
          			}
             }
          }
        }
    }
    &#13;
    &#13;
    &#13;