PHP验证多个必填字段

时间:2018-08-22 22:12:21

标签: php

在发送电子邮件之前,我正在验证一些输入字段。我正在使用每个循环来更快地遍历数组,并检查每个输入是否为空,并将其作为jquery的响应返回以显示错误。问题是emailmessage的输入未得到验证。即使输入为空,也会发送电子邮件。

数组元素来自html的输入名称属性。

function e_($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

#required fields
$required = array('name', 'email','lname','message','country' , 'city' ,'adcategory','plan' ,'company');
$success = false;

#non required fields
$website = e_($_POST['website']);
$addr = e_($_POST['address']);

foreach($required as $field) {
    if (empty($_POST[$field]))
    {
        $success = false;
    }
    else if(!empty($_POST[$field])){
        $success = true;
        $name = e_($_POST['fname']);
        $email = e_($_POST['email']); #this has issue
        $lname = e_($_POST['lname']);
        $msg = e_($_POST['message']); #this has issue

        $country = e_($_POST['country']);
        $city = e_($_POST['city']);
        $adCategory = e_($_POST['adcategory']);
        $plan = e_($_POST['plan']);
        $companyName = e_($_POST['company']);
    }

}

if($success)        
    echo "success";
else if (!$success)
    echo json_encode(['errors'=>true]); #this will be manipulated in jquery

2 个答案:

答案 0 :(得分:2)

问题在于,只要找到必填字段,便会设置$success = true;,这会使上一个字段的$success = false;撤消。您还处理else if中的 all 个字段,即使这只是意味着找到了一个个必填字段。

$success = true;
foreach ($required as $field) {
    if (empty($_POST[$field])) {
        $success = false;
        $missing_field = $field;
        break;
    }
}

if (!$success) {
    echo json_encode(['errors'=>true, 'missing' => $missing_field]);
    exit();
}

$name = e_($_POST['fname']);
$email = e_($_POST['email']); #this has issue
$lname = e_($_POST['lname']);
$msg = e_($_POST['message']); #this has issue

$country = e_($_POST['country']);
$city = e_($_POST['city']);
$adCategory = e_($_POST['adcategory']);
$plan = e_($_POST['plan']);
$companyName = e_($_POST['company']);
echo "Success";

答案 1 :(得分:1)

您的foreach循环是错误的。您的if语句中有一个if语句,用于检查它是否不为空。您需要先检查所有值是否为空,然后运行if语句。

$success = true;
foreach($required as $field) {
    if (empty($_POST[$field]))
    {
        $success = false;
        break;
    }
}

if($success)
{
    // set your variables
} else {
    // don't set your variables
}