CodeIgniter对非来自表单的变量/输入进行验证


CodeIgniter validation of variables / input not coming from form?

让我们假设我有用户生成的数据,这些数据不是通过表单发布的。有没有一种方法可以使用/扩展CodeIgnitors form_validation类来验证该数据。

例如。

<?php
$userData = array('name' => 'tt' , 'city' => 'London' , 'age' => '1200' );
// How can I validate this data using form_validation checks
// like min_length,max_length,and apply some processing
// like trim,xss_clean provided by the same class
?>

是的,你可以通过set_data()方法,给你。

$this->form_validation->set_data(array(
        'name'    =>  'Full Name',
        'city'    =>  'City',
));
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('city', 'City', 'trim|required');
$this->form_validation->set_rules('age', 'Age', 'trim|required');
if ($this->form_validation->run() == FALSE) {
    echo 'Invalid: ' . validation_errors();
} else {
    echo 'Valid';
}

您可以扩展codeigniter的核心表单验证库的run和set_rule方法。这是我在不扩展核心的情况下如何做到的:

  // Data coming from backbone model  
     $data = json_decode(file_get_contents('php://input'), true); 
     $this->config->load('myValidConf/form_validation');
     $non_post = array(
           'foo' => $data['foo']
      );
     $_POST = $non_post; 
     if ($this->form_validation->run('myConfigarray')!== FALSE) {
            echo 'we're ok';
     } else {
         echo validation_errors() ;
     }

希望它能帮助你。

听起来像是一个肮脏的黑客,但你可以通过设置$_post数据来欺骗表单帖子?假设您收到JSON,您可以执行以下操作:

$json = "...."; //json encoded string
$arr = json_decode($json, true);
foreach($arr as $key => $value)
{
    $_POST[$key] => $value;
}
// do form validation as if the data was posted from a form.

这当然只是个权宜之计。您可以扩展/覆盖Form_validation库的部分内容。我会怎么做:

  • 添加MY_Form_validation.php库,复制粘贴Form_validationphp中使用$_POSTset_rules()run()matches())的所有函数
  • 将MY_Form_validation.php中$_POST的所有实例替换为$this->validate_data
  • 在构造函数中将$validate_data设置为$_POST
  • 添加一个函数set_validate_data(),允许您覆盖$this->validate_data

如果要使用已清理的数据,则必须在验证数据后使用$_POST数组。如果这是不可接受的,还可以添加一个函数来清理$this->validate_data并返回一个XSS清理数组。