for-each循环用于表单验证

时间:2015-08-24 15:46:42

标签: php html forms validation foreach

好的,所以我在一个有很多行(20+)和每行4个字段的表单上做了一些验证。

  • 每列都有特定的验证要求
  • 行应该是完整的,而不是半满的。应跳过空行

如果html表单中的每个字段都有唯一的名称,如何遍历表单。例如productCode_1,productCode_2,productCode_3等..

 <tr>
<td><div align="center">
  <input name="productCode_1" type="text" id="productCode_1" size="7" maxlength="7" />
</div></td>
<td><div align="center">
  <input name="size_1" type="text" id="size_1" size="2" maxlength="2" />
</div></td>
<td><div align="center">
    <input name="quantity_1" type="text" id="quantity_1" size="3" maxlength="3" />
</div></td>
<td><div align="center">
    <input name="price_1" type="text" id="price_1" size="3" maxlength="3" />
</div></td>

以上是HTML的示例,请注意我无权修改HTML。

2 个答案:

答案 0 :(得分:1)

你要在数组中放置你想要验证的字段的字段名称,然后它将循环遍历它们。我已经进行了简单的empty检查,但是你会添加自己的复杂检查。

    // All the names of the fields you wish to validate.
    $myFieldNames = [];
    $hasErrorOccurred = false;

    foreach ($myFieldNames as $name) {
        if (empty($_POST[$name])) {
            $hasErrorOccurred = true;

            break;
        }
    }

    if ($hasErrorOccurred) {
        // Your error code here.
    } else {
        // Your successful code here.
    }

阅读材料:

break;

答案 1 :(得分:1)

我假设如果您显示的HTML行数为20行,那么名称=“..”的名称将类似于productCode_1productCode_2等。

$fields = array('productCode_', 'size_', 'quantity_', 'price_');
$msg = array();  // for error messages
$max_rows = ?; // how many rows to check, cannot see enough of your code to work this one out for you


$ok = true;
for ( $i=1; $i < $max_rows; $i++ ) {

    foreach ( $fields as $field ) {
        if ( ! isset( $field . $i ) )
            $ok = false;
            $msgs[] = "Missing data in $field on row $i";
            // continue is optional, if set will stop processing a row
            // when first error is found, 
            // without it you can report all errors on each row
            continue;   
    }

}

if ( $ok ) {
    // complete form processing
} else {

    // report back all errors
}