PHP - How to validate select option server side?

2019-10-05 07:13发布

问题:

I have a form that has a option, in which the user is required to select a State. How can I validate this, server-side, with pure PHP? If the "Select State" option is selected, then server will return "not valid".

Thank you!

My HTML code (summary):

<select id="stateSel" name="state" onclick="stateValidation()">
        <option value="0">Select State</option> /*will return as invalid option*/
        <option value="AL">Alabama</option>
        <option value="AK">Alaska</option>
        <option value="AZ">Arizona</option>
        /*[etc, options for each state]*/
        <option value="WY">Wyoming</option>
</select>

回答1:

You can do it like this:

<?php
$valudStates = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 
                'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 
                'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 
                'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 
                'WV', 'WI', 'WY'];
if (isset($_POST['state']) && in_array($_POST['state'], $valudStates)){
    //code for valide state
} else {
    //code for NOT valide state
}

here the code not only checks if there is a post field state but also it is comparing with possible values (in this case US states).



回答2:

Value of only selected option is posted to server side when you submit a form.

If you are submitting form with POST method.

<?php

if( $_POST['state'] == "0" ) {
  // not valid
}

?>


回答3:

State's default value is always 0 at load time if user didn't change it then you need to validate like below code

BELOW CODE IS FOR FORM SUBMIT

<?php
if( $_POST['state'] == "0" ) {
  echo "Please select the state field";
}else{
  echo "Your selected state is ".$_POST['state'];//just for example purpose
}
die;
?>

OR

BELOW CODE IS FOR JS FUNCTION

<select id="stateSel" name="state" onclick="stateValidation(this.id)">
        <option value="0">Select State</option> /*will return as invalid option*/
        <option value="AL">Alabama</option>
        <option value="AK">Alaska</option>
        <option value="AZ">Arizona</option>
        <option value="WY">Wyoming</option>
</select>
function stateValidation(id){
    var state = $('#'+id+'option:selected').val();
    if(state == '0'){
       alert("Please select the state field");
    }else{
       alert("Your selected state is "+state);
    }
}