Validate a multi select input field in HTML using PHP and JavaScript
I have a select input field in multiple 开发者_如何学编程properties. I have to validate (empty check) this field in both JavaScript and PHP. My code is like:
select multiple="multiple" name="frm_supply[]>
Let's say you have an HTML code like this:
<select multiple="multiple" name="frm_supply[]">
<option value="s1v1">A</option>
<option value="s1v2">B</option>
<option value="s1v3">C</option>
</select>
<select multiple="multiple" name="frm_supply[]">
<option value="s2v1">1</option>
<option value="s2v2">2</option>
<option value="s2v3">3</option>
</select>
When submitting the form, if A, B and 1 are checked, $_POST
array will be like this:
Array (
[frm_supply] => Array (
[0] => s1v1
[1] => s1v2
[2] => s2v1
)
)
So, check trough a loop if any <select/> is empty. The following code walks through two <select/>s and displays for each either "List N has values" or "List N is empty".
$countValuesPerList = array();
foreach ($_POST['frm_supply'] as $key => $value)
{
$index = substr($value, 1, strpos($value, 'v') - 1);
$countValuesPerList[$index] = true;
}
for ($i = 1; $i <= 2; $i++)
{
echo isset($countValuesPerList[$i]) && $countValuesPerList[$i] ? 'List ' . $i . ' has values' : 'List ' . $i . ' is empty';
}
Now, to check selections on client side, proceed the same way and check what is selected in each <select/>.
multiple selection values are stored in a array . so check the length of the array and according to ur validation rule, for example for atleast 2 selection ,the length of the array should be greater than 2 and so on
<select name="name">
<?php
for ($i = 0; $i < $count; $i++) {
echo '<option value='$i'>$i</option>';
}
?>
</select>
精彩评论