【问题标题】:php form validation using prerequisite使用先决条件的 php 表单验证
【发布时间】:2013-05-04 15:55:42
【问题描述】:

我正在尝试验证表单中的某些字段。我正在使用“地址”和“州”两个字段,最初“地址”和“州”字段不是强制性的,但如果在“地址”字段中输入任何值,则“州”字段(这是一个选择list) 自动成为强制性的。我只是不确定如何编写正确的 IF 条件。

这是我开始的:

<?php

if (isset($_POST["submit"])) {

$address = $_POST["address"];
$address = trim($address);
$lengtha = strlen($address);
$post = $_POST["post"];
$state = $_POST["state"];

if ($lengtha > 1) {

?>

<form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="custinfo" >
<table>
<tr>
    <td><label for="custid">Customer ID (integer value): </label></td>
    <td><input type="text" id="custid" name="custid" value="<?php echo $temp ?>" size=11 /><?php echo $msg; ?></td>
</tr>

<tr>
    <td><label for="customerfname">Customer First Name: </label></td>
    <td><input type="text" id="fname" name="fname" size=50/><?php echo $strmsg; ?></td>
</tr>
<tr>
    <td><label for="customerlname">Customer Last Name: </label></td>
    <td><input type="text" id="lname" name="lname" size=50/><?php echo $strmsgl; ?></td>
</tr>
   <tr>
    <td><label for="customeraddress">Customer Address: </label></td>
    <td><input type="text" id="address" name="address" size=65/></td>

    <td><label for="suburb"> Suburb: </label></td>
<td><input type="text" id="suburb" name="suburb"/></td>
</tr>
<tr>
<td>
State:<select name="state" id="state">
    <option value="select">--</option>
    <option value="ACT">ACT</option>
    <option value="NSW">NSW</option>
    <option value="NT">NT</option>
    <option value="QLD">QLD</option>
    <option value="SA">SA</option>
    <option value="TAS">TAS</option>
    <option value="VIC">VIC</option>
     <option value="WA">WA</option>
   </select>
</td>

任何解决这个问题的帮助都会很棒!

【问题讨论】:

    标签: php forms validation selection prerequisites


    【解决方案1】:

    基本上,当且仅当地址字段不为空时,您只需要验证您的状态字段。这可以通过以下代码实现:

    if ( isset( $_POST[ 'address' ] ) && ! empty( $_POST[ 'address' ] ) ) {
        // An address has been provided, so validate the state.
        if ( ! isset( $_POST[ 'state' ] ) || ! in_array( $_POST[ 'state' ], $valid_states ) ) {
            // There was an error: the address is set but the state is not.
        }
    }
    

    请记住,上述代码中的$valid_states 表示表单应接受的选择列表中的所有状态值的数组。例如:

    $valid_states = array(
        'KY', 'IL', 'FL', 'WY', /* ... */
    );
    

    如果地址字段未填充,您还可以在表单中添加一些 JavaScript 以完全隐藏状态字段。由于只有在填充地址时才会验证状态,所以它在表单上的存在无关紧要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-25
      • 1970-01-01
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      • 2015-06-15
      • 2015-11-30
      • 2021-02-01
      相关资源
      最近更新 更多