Question

i am trying to validate some fields in my form. I am working with two fields, "address" and "state", initially the "address" and "state" field are not compulsory but if any value is entered into the "address" field the "state" field (which is a selection list) automatically becomes compulsory. I am just unsure on how to code the right IF condition.

Here is what i have started on:

<?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>

Any help with figuring this out would be great!

Was it helpful?

Solution

Essentially, you just need to validate your state field if and only if the address field is not empty. This can be achieved with the following code:

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.
    }
}

Keep in mind that $valid_states in the above code represents an array of all the state values from the select list that should be accepted by the form. For example:

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

You could also add some JavaScript to your form to completely hide the state field if the address field is not populated. Since state will only be validated if address is populated, it's existence on the form will not matter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top