PHP表单验证使用先决条件


php form validation using prerequisite

我正在尝试验证我的表单中的一些字段。我工作与两个字段,"地址"answers"状态",最初的"地址"answers"状态"字段不是强制性的,但如果任何值被输入到"地址"字段的"状态"字段(这是一个选择列表)自动成为强制性的。我只是不确定如何编码正确的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>

任何有助于解决这个问题的帮助将是伟大的!

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

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,以便在地址字段未填充时完全隐藏状态字段。因为state只有在address被填充时才会被验证,所以它在表单上是否存在并不重要。