How to validate select items with PHP?

Asked by: chris11
Date:
Viewed: 405
Answers: 1
  • 0

Hi,

I have a dropdown select list. How can I validate it with PHP?

Answers

Answer by: jenniryan

Answered on: 21 Jul 2023

  • 0

Let’s assume you have a form with a select list like this:

<select class="form-select" name="gender">
   <option selected value="">--Select Gender--</option>
   <option value="Male">Male</option>
   <option value="Female">Female</option>
</select>

In your php file you can validate it like this:

$genders = ['Male','Female'];
if(empty($_POST['gender']))
{
   $info['errors']['gender'] = "A gender is required";
}else
   if(!in_array($_POST['gender'], $genders))
   {
   $info['errors']['gender'] = "Gender is not valid";
}

So basically we check whether the value for the “gender” field has been submitted via the form, and whether that value is one of the allowed genders (“Male” or “Female”).

First we create an array called “$genders” that contains the allowed values for the “gender” field. In this case, the allowed values are “Male” and “Female”.

The first if block checks whether the “gender” field has been submitted via the form (i.e., whether it is not empty). If the field is empty, it adds an error message to an array called “$info[‘errors’]” with the key “gender”, indicating that a value for the “gender” field is required.

If the “gender” field is not empty, the else if block checks whether the submitted value is one of the allowed values in the “$genders” array. If the submitted value is not one of the allowed values, it adds an error message to the “$info[‘errors’]” array with the key “gender”, indicating that the submitted value is not valid.

Overall, this code ensures that the submitted value for the “gender” field is either “Male” or “Female”, and if it’s not, it adds an error message to be displayed to the user.

You can display the error message like this:

<select class="form-select" name="gender">
   <option selected value="">--Select Gender--</option>
   <option value="Male">Male</option>
   <option value="Female">Female</option>
</select>

<?php if(isset($info['errors']['gender'])) { ?>
   <p class="error"><?php echo $info['errors']['gender']; ?></p>
<?php } ?>

If an error message exists, we output a paragraph element with a class of “error”, and use the “echo” function to output the error message from the array.

Note that the exact implementation of how to display the error message to the user may vary depending on your specific use case and the design of your form.

Please log in to post an answer!