Reputation: 23
I'm trying to validate a form in PHP. I have instructions not to change the form itself (The names of the fields for example) and in it there is a drop down list with this:
<option value=""></option>
I tried to validate with this :
if (!isset($_POST['cboproduit'])){
$message.= "Vous devez sélectionner un téléphone <br />";}
but since there is a value with nothing in it, if I submit the form with the empty value it just saves an empty value.
How can I do this in a simple way?
Upvotes: 0
Views: 2683
Reputation: 1
Just a thought but empty may not work for you because the value attribute of <option value=""></option>
may be set to 0 for the first element (1 as the second and so on) and then this would mean that you could never delete the 0th element as empty checks for 0 and also for empty
if (empty($_POST['cboproduit'])){
$message.= "Vous devez sélectionner un téléphone <br />";
}
Upvotes: 0
Reputation: 781004
In addition to checking if the variable is set, you need to check if it's not empty:
if (!isset($_POST['cboproduit']) || $_POST['cboproduit'] === '') {
$message .= "Vous devez sélectionner un téléphone <br />";
}
Upvotes: 2
Reputation: 2715
Different functions check different things about a variable. According to the documentation:
isset()
: Determine if a variable is set and is not NULL.empty()
: A variable is considered empty if it does not exist or if its value equals FALSE.array_key_exists()
: returns TRUE if the given key is set in the arraySo in your case, if (empty($_POST['cboproduit']))
seems the best way to proceed. It will detect if the value was somehow not transmitted (someone could edit the form in their browser before submitting it) or the empty option was selected.
(Note that this means that there is no way to determine the difference between a variable that does not exist and a variable that is null
.)
Upvotes: 0