使用数组进行Php表单验证-打印变量名称

使用数组进行Php表单验证-打印变量名称,php,arrays,validation,Php,Arrays,Validation,我试图通过将post值放入变量中,将这些变量放入数组中,然后在其中循环,并输出未填充字段的错误消息来进行表单验证。 我有两个问题。首先,if语句正在为所有值运行,即使该字段为空或为==to'undefined',其次,我不知道如何打印变量的实际名称而不是变量值。比如说 $variable = 'hello'; print\u x($variable)//打印“variable”而不是“hello” 我尝试了两种方法,如下所示 $error_message = "The following

我试图通过将post值放入变量中,将这些变量放入数组中,然后在其中循环,并输出未填充字段的错误消息来进行表单验证。 我有两个问题。首先,if语句正在为所有值运行,即使该字段为空或为==to'undefined',其次,我不知道如何打印变量的实际名称而不是变量值。比如说

$variable = 'hello';
print\u x($variable)//打印“variable”而不是“hello”

我尝试了两种方法,如下所示

   $error_message = "The following fields must be filled in:<br />";
        $fields_to_validate_arr = array($category,$producer,$product_name,$image_name,$description,$stock_quantity,$min_sale);
        foreach($fields_to_validate_arr as $v){
            if(empty($v) || $v = 'undefined'){//using variable bariables
                //increment the error message with a custom error message. 
                $error_message .= "->" . ucwords(str_replace('_',' ',$v)) . "<br />";//no need to use variable variables
            }
        }

谢谢

当您的第一个代码块出现时,您的IF语句中有一个bug。您正在设置$v='undefined',它每次都会计算为true。您需要对IF语句使用相等运算符

   $error_message = "The following fields must be filled in:<br />";
   $fields_to_validate_arr = array($category,$producer,$product_name,$image_name,$description,$stock_quantity,$min_sale);
   foreach($fields_to_validate_arr as $v){
       if(empty($v)){ //using variable variables
           //increment the error message with a custom error message. 
           $error_message .= "->" . ucwords(str_replace('_',' ',$v)) . "<br />";//no need to use variable variables
       }
   }
$error\u message=“必须填写以下字段:
”; $fields\u to\u validate\u arr=数组($category、$producer、$product\u name、$image\u name、$description、$stock\u quantity、$min\u sale); foreach($v字段\u到\u验证\u arr){ if(空($v)){//使用变量 //使用自定义错误消息增加错误消息。 $error_message.=“->”。ucwords(str_replace(“”,“”,“”,$v))。“
”;//无需使用变量 } }
无需创建自己的输入变量数组,因为您已经拥有$\u POST:

$_POST = array_map('myescape_function', $_POST);
foreach($fields_to_validate_arr as $v){
    if(empty($_POST[$v]) || $_POST[$v] == 'undefined'){
       //increment the error message with a custom error message. 
       $error_message .= "->" . ucwords(str_replace('_',' ',$v)) . "<br />";
    }
}
$\u POST=array\u map('myescape\u函数',$\u POST);
foreach($v字段\u到\u验证\u arr){
如果(空($_POST[$v])|$|$_POST[$v]==‘未定义’){
//使用自定义错误消息增加错误消息。
$error_message.=“->”。ucwords(str_replace(“”,“”,“”,$v))。“
”; } }
由于值不存储在单独的变量中,因此打印变量名称而不是其值的问题就消失了

如果您想获得真正的乐趣,可以添加对自定义验证器的支持:

function inputExists($name, &$source) {
    return !empty($source[$name]) && 'undefined' != $source[$name];
}
function inputIsNumeric($name, &$source) {
    return inputExists($name, $source) && is_numeric($source[$name]);
}
// checks for U.S. phone numbers only
function inputIsPhone($name, &$source) {
    if (inputExists($name, $source)) {
        // strip whatever non-numeric 
        $value = preg_replace('/[-.,() \t]+/', '', $source[$name]);
        return preg_match('^(1?[2-9]\d{2})?[2-9]\d{6}$', $value);
    }
    return False;
}
function inputMatchesRE($name, &$source, $RE) {
    return inputExists($name, $source) && preg_match($RE, $source[$name]);
}
function nameAndValidator($name, $validator) {
    if (function_exists($validator)) {
        return array('name' => $name, 'validator' => $validator, 'data' => '');
    } elseif (is_numeric($name)) {
        // if index is numeric, assume $validator actually holds the name
        return array('name' => $validator, 'validator' => 'inputExists', 'data' => '');
    } else {
        return array('name' => $name, 'validator' => 'inputMatchesRE', 'data' => $validator);
    }
}

$fields_to_validate_arr = array('name', 'street' => '/^\d+ +[a-z ]+(ave|st|wy|way|ln|lp|blvd)$/i', 'age'=> 'inputIsNumeric', 'phone' => 'inputIsPhone');

$_POST = array_map('myescape_function', $_POST);

foreach($fields_to_validate_arr as $name => $validator){
    list($name, $validator, $data) = nameAndValidator($name, $validator);
    if(! call_user_func($validator, $name, $_POST, $data)){
       //increment the error message with a custom error message. 
       $error_message .= "->" . ucwords(str_replace('_',' ',$v)) . "<br />";
    }
}
函数输入存在($name,&$source){
return!空($source[$name])&&“未定义”!=$source[$name];
}
函数inputIsNumeric($name,&$source){
返回inputExists($name,$source)&&is_numeric($source[$name]);
}
//仅检查美国电话号码
函数inputIsPhone($name,&$source){
if(inputExists($name,$source)){
//去掉任何非数字的
$value=preg_replace('/[-,()\t]+/','','$source[$name]);
返回preg_match('^(1?[2-9]\d{2})][2-9]\d{6}$',$value);
}
返回False;
}
函数inputMatchesRE($name,&$source,$RE){
返回inputExists($name,$source)和&preg_match($RE,$source[$name]);
}
函数名和验证器($name,$validator){
如果(函数_存在($validator)){
返回数组('name'=>$name,'validator'=>$validator,'data'=>'');
}elseif(是数字($name)){
//如果索引是数字的,则假定$validator实际持有该名称
返回数组('name'=>$validator,'validator'=>'inputExists','data'=>'';
}否则{
返回数组('name'=>$name,'validator'=>'inputMatchesRE','data'=>$validator);
}
}
$fields_to_validate_arr=array('name','street'=>'/^\d++[a-z]+(ave|st|wy | way | ln | lp | blvd)$/i','age'=>'inputIsNumeric','phone'=>'inputIsPhone');
$\u POST=array\u map('myescape\u函数',$\u POST);
foreach($fields\u to\u validate\u arr as$name=>$validator){
列表($name,$validator,$data)=name和validator($name,$validator);
如果(!call_user_func($validator,$name,$\u POST,$data)){
//使用自定义错误消息增加错误消息。
$error_message.=“->”。ucwords(str_replace(“”,“”,“”,$v))。“
”; } }
我看不到它们,它们是什么?修复第一个bug在值等于“undefined”时修复了它,但当变量为空时,我仍然得到错误响应。我应该使用$v=''”;?有什么区别吗?你应该只需要对空($v)进行一次检查,就可以删除第二次检查。Empty处理isset()和!=''的两种情况所以您不需要进行二次检查。@安德鲁:注意,在使用
=
赋值的语言中,您可以通过始终将变量放在比较运算符之后来防止上述错误
'undefined'=$v
无效,将生成一个错误,间接提醒您输入错误。就我个人而言,我会使用ctype_digit或类似的东西,而不是像is_digital那样接受科学符号、十六进制等(这不是大多数人在验证表单时寻找的)。
$_POST = array_map('myescape_function', $_POST);
foreach($fields_to_validate_arr as $v){
    if(empty($_POST[$v]) || $_POST[$v] == 'undefined'){
       //increment the error message with a custom error message. 
       $error_message .= "->" . ucwords(str_replace('_',' ',$v)) . "<br />";
    }
}
function inputExists($name, &$source) {
    return !empty($source[$name]) && 'undefined' != $source[$name];
}
function inputIsNumeric($name, &$source) {
    return inputExists($name, $source) && is_numeric($source[$name]);
}
// checks for U.S. phone numbers only
function inputIsPhone($name, &$source) {
    if (inputExists($name, $source)) {
        // strip whatever non-numeric 
        $value = preg_replace('/[-.,() \t]+/', '', $source[$name]);
        return preg_match('^(1?[2-9]\d{2})?[2-9]\d{6}$', $value);
    }
    return False;
}
function inputMatchesRE($name, &$source, $RE) {
    return inputExists($name, $source) && preg_match($RE, $source[$name]);
}
function nameAndValidator($name, $validator) {
    if (function_exists($validator)) {
        return array('name' => $name, 'validator' => $validator, 'data' => '');
    } elseif (is_numeric($name)) {
        // if index is numeric, assume $validator actually holds the name
        return array('name' => $validator, 'validator' => 'inputExists', 'data' => '');
    } else {
        return array('name' => $name, 'validator' => 'inputMatchesRE', 'data' => $validator);
    }
}

$fields_to_validate_arr = array('name', 'street' => '/^\d+ +[a-z ]+(ave|st|wy|way|ln|lp|blvd)$/i', 'age'=> 'inputIsNumeric', 'phone' => 'inputIsPhone');

$_POST = array_map('myescape_function', $_POST);

foreach($fields_to_validate_arr as $name => $validator){
    list($name, $validator, $data) = nameAndValidator($name, $validator);
    if(! call_user_func($validator, $name, $_POST, $data)){
       //increment the error message with a custom error message. 
       $error_message .= "->" . ucwords(str_replace('_',' ',$v)) . "<br />";
    }
}