First of all, I have already readed this: Validating form dropdown in CodeIgniter
But it doesnt solve my problem:
As you know, <option> value can be faked for example using firebug.
My select options looks like this:
<option value="ger">Germany</option>
<option value="uk">United Kingdom</option>
<option value="usa">United States of America</option>
[...]
Now, how can I validate if the choosen and posted value is correct?
These values are builded on the large array. It looks following:
$countries = array (
'ger' => 'Germany',
'uk' => 'United Kingdom',
'usa' => 'United States of America'
);
So how can I validate, of choosen value is correct? Will I have to use the array_key_exist with function callback on form validation?
What in case if my select options looks like this?
<option value="0">Choose Something</option>
<option value="1">Select-1</option>
<option value="2">Select-2</option>
[..]
How can I validate the above using the form validator, so I could check if the posted value is correct and not faked, also how to prevent from choosing the 0 value?
The best idea for this in my opinion is creating the function callback, which will look following:
public function validate_values($input)
{
$allowed = array(1, 2, 3, 4); //[..]
if ( !in_array( $input, $allowed ) )
{
//throw error, and do the rest...
}
}
Are my ideas “ok” or there are any better solutions for these cases?
The callback is exactly what you need. I think that’s why they were created. In user guide:
So if your need is to check if submitted values are from defined range, use it.
Of course it should return false or true depending on result. user guide for callbacks
For me it’s the best solution. Especially because you need to check those values after form is submitted.
As for preventing from choosing 0, don’t put 0 to
in_arrayor check first if$inputis!emptyfor example and set correct error message. If you’re creating your own callback you can validate that$inputfor whatever you want.