1

由于某些原因,我的 javascript 表单验证不会遍历表中的每一行。我使用以下代码创建了表: $usr 变量只是另一个进程的结果:

<form name="myForm" action="addAccessories.php"  method="post" onsubmit="return validateForm(this);">
        <table border="1" id="IT">
            <tr> 
                <th>Barcode<em>*</em></th>
                <th>Current stock</th>
            </tr>    
        <?php
           for($id=1; $id<=$usr; $id++){                   
        ?>
            <tr>                    
                <td><input type="hidden"  name="id[]" value="<?php echo $id; ?>" />
                    <input type="text"  name="bar_code<?php echo $id; ?>" id="bar_code<?php echo $id; ?>" value="" /></td>                  
                <td><input type="text"  name="num_stock<?php echo $id; ?>" value="0" id="num_stock<?php echo $id; ?>"/></td>
        <?php
            }
        ?>
            <tr>
                <td> </td> 
                <td> <button data-theme="b" input type="submit" name="Submit" value="Submit">Add accessories</button></td>
            </tr>
        </table>
    </form> 

该表的行数为:rows = $usr + 1

我的验证表单代码:

<script type="text/javascript">           
function validateForm(){    
var errors = [];        
for(i = 1; i < document.getElementById("IT").rows.length; i++){
      var barcode = document.getElementById('bar_code'+i).value;
    var des = document.getElementById('description'+i).value;
    var num_stock =  document.getElementById('num_stock'+i).value;        

    if(barcode == null || barcode == ""){
        errors[errors.length] = "You must enter barcode.";
    } 
  if(isNaN(num_stock)){
        errors[errors.length] = "Current stock must be an integer";
    } 
    if(num_stock < 0){
        errors[errors.length] = "Current stock must be a positive number";
    } 

    if (errors.length > 0) {
    reportErrors(errors);
    return false;
    }
    return true;
    }
}
function reportErrors(errors){
var msg = "There were some problems...\n";
for (var i = 0; i<errors.length; i++) {
    var numError = i + 1;
    msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>

此过程仅验证表中的第一行然后停止。谁能告诉我出了什么问题以及如何解决?非常感谢您的帮助

4

1 回答 1

0

你的代码让生活变得比它需要的更复杂。一种更简单的方法是只处理表单控件,例如,因为您已经从提交侦听器传递了对表单的引用:

function validateForm(form) {
  var errors = [];
  var c, cs = form.elements;
  var reB = /^bar_code/;
  var reN = /^num_stock/;
  var reD = /^[0-9]+$/;

  for (var i=0, iLen=cs.length; i<iLen; i++) {
    c = cs[i];

    if (reB.test(c.name) && c.value == '') {
      errors.push('You must enter barcode.'];

    } else if (reN.test(c.name) && !reD.test(c.value)) {
      errors.push('Stock number must be a positive integer.'];
    }       
  }

  // deal with errors...

}

请注意,在测试中:

> barcode == null || barcode == ""

条形码是一个字符串,因此第一个测试永远不会返回 true,如果您想查看它是否为空,第二个就足够了。

于 2012-06-09T05:33:07.287 回答