Share
How to validate select items with PHP?
Question
Hi,
I have a dropdown select list. How can I validate it with PHP?
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Answer ( 1 )
Let’s assume you have a form with a select list like this:
In your php file you can validate it like this:
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:
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.