繁体   English   中英

PHP表单验证与数组-打印变量名称

[英]Php form validation with an array - print the name of a variable

我试图通过将post值放入变量并将那些变量放入数组中,然后循环遍历它们并为未填写的字段输出错误消息来进行表单验证。我遇到两个问题。 首先,即使该字段为空或==到“未定义”,if语句也会为所有值运行,其次,我不知道如何打印出变量的实际名称而不是变量值。 例如

$variable = 'hello';

print_x($variable)//prints 'variable' instead of '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
            }
        }

还有一种使用变量变量的方法

$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
        }
    }

变量在我的代码中进一步分配,例如

$category = myescape_function($_POST['category']);

谢谢

就您的第一个代码块而言,您的IF语句中有一个错误。 您正在设置$ 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
       }
   }

无需创建自己的输入变量数组,因为您已经有$ _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 />";
    }
}

由于值没有存储在单独的变量中,因此打印变量名而不是值的问题就消除了。

如果您真的想花哨的话,可以添加对自定义验证器的支持:

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 />";
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM