Array as required field in PHP form not recognized
I've got a PHP e-mail form to which I've just added an array of checkboxes. Data is coming through fine. Ho开发者_StackOverflowwever I want to make it so users have to click at least one of the checkboxes, but the current code I'm using to require fields isn't working for the checkboxes. The array of checkboxes is called 'formOptions'. This is the code I'm using:
$allowedFields = array(
'name',
'company',
'email',
'phone',
'comments',
'output',
'formOptions',
);
// Specify the field names that you want to require...
$requiredFields = array(
'name',
'email',
'phone',
'formOptions',
);
// Loop through the $_POST array, which comes from the form...
$errors = array();
foreach($_POST AS $key => $value)
{
// first need to make sure this is an allowed field
if(in_array($key, $allowedFields))
{
$$key = $value;
// is this a required field?
if(in_array($key, $requiredFields) && $value == '')
{
$errors[] = "$key, ";
}
}
}
You might want to test for empty()
instead of $value == ''
.
But the real problem is that you're not testing any $_POST
variables that aren't set. So while you ensure that a required field is not empty, it won't check a field that was not even passed to the script. Which is what happens when the checkboxes aren't checked, it's not that $_POST['formOptions']
is empty, it's that there is no $_POST['formOptions']
.
Instead of looping through the $_POST
array, you would need to loop through the $requiredFields
array.
foreach($requiredFields as $field){
if(empty($_POST[$field])){
//$field is missing
}
}
If you don't want to change the current structure, you could just unset each $requiredFields
when it's found, then if $requiredFields
has any members left, they are the missing fields.
Using your example code:
foreach($_POST AS $key => $value)
{
// is this a required field?
if(in_array($key, $requiredFields))
{
if(empty($value)){
//$key is missing
}
unset($requiredFields[array_search($key)];
}
}
//$requiredFields contains any missing fields
Or you could also just set some default values (null
would work), and keep your exsisting code:
$requiredFields = array(
'name' => null,
'email' => null,
'phone' => null,
'formOptions' => null,
);
$_POST = array_merge($requiredFields, $_POST);
//any missing required field is now null
Then you just need to change your 'is required' check to:
if(array_key_exists($key, $requiredFields) && $value == '')
Note that I haven't tested any of the code samples.
You could use :
if(in_array($key, $requiredFields) && !$value)
and it should work
Edit:
it shouldn't work. you need to place the loop that checks for required fields outside the loop for $_post. to make sure you can check if a post key never exist. see the comments below. see Tim comment.
精彩评论