0
public function registration()
    {
    $this->load->library('form_validation');
    // field name, error message, validation rules
    $this->form_validation->set_rules('user_name', 'User Name', 'trim|required|min_length[4]|xss_clean');
    $this->form_validation->set_rules('email_address', 'Your Email', 'trim|required|valid_email');`enter code here`
    $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
    $this->form_validation->set_rules('con_password', 'Password Confirmation', 'trim|required|matches[password]');
        }

我已经在执行验证的 codeigniter 中做到了这一点。我如何在 php native 中做类似的工作?我的意思是验证

4

2 回答 2

0

您可以通过 php 变量访问发布的表单值$_POST。然后,您需要在 php 中编写执行不同验证的函数:-

这些应该让你开始,其余的看看 codeigniter 是如何做的,或者一篇关于使用 php 进行服务器端验证的文章。

希望这可以帮助!

于 2012-04-26T10:32:21.353 回答
0

我过去的做法是为它构建对象……一个表单对象、一个表单字段对象和一个表单字段验证器对象。

因此,您将创建所有字段对象,并在需要时将验证器附加到它们,然后将全部附加到表单 - 所以您最终会得到如下内容:

$oFieldUsername = new FormField('username', new Validator(Validator::TYPE_EMAIL));
$oFieldPassword = new FormField('password', new Validator(Validator::TYPE_PASSWORD));

$oForm = new Form(Form::METHOD_POST, '/path/to/action.php');
$oForm->attachField($oFieldUsername);
$oForm->attachField($oFieldPassword);

//form has not been posted
if(!$oForm->isReceived()) {
  $oForm->render('/path/to/view.tpl.php');
}

//the form HAS been posted but IS NOT VALID
elseif(!$oForm->isValid()) {
  $oForm->render('/path/to/view.tpl.php');
}

//the form HAS been posted and the data LOOKS valid
else {
  //do processing and hand-off
}

验证器处理诸如确定是否需要字段数据,如果数据与空字符串 (RegExp) 匹配,则例如不需要。

但他们也可以处理电子邮件验证(有或没有 getmxrr() 查找)或其他任何事情,您只需为特定情况构建验证器类型......或者您有通用验证器:

new Validator(Validator::TYPE_EMAIL); //basic email validator
new Validator(Validator::TYPE_EMAIL_WITH_MX); //email validator with getmxrr()
new Validator(Validator::TYPE_REGEXP, '/^[\w]+$/'); //generic regular expression with the pattern to match as the second parameter
new Validator(Validator::TYPE_INT_MIN, 10); //integer with a minimum value of 10
new Validator(Validator::TYPE_REGEXP, '/^[\w\s]*$/', true); //the third parameter could be an override so that the validation is optional - if the field has a value it MUST validate, if it doesn't have a value, it's fine

这为您提供了所需的验证灵活性。该Form::isValid()方法所做的只是遍历所有附加字段,检查它们是否有验证器,如果有,该Validator::isValid()方法是否返回 true。

您还可以使用以下内容将多个验证器附加到字段:

//the field value must be an integer between 5 and 10 (inclusive)
$oField->addValidator(new Validator(Validator::TYPE_INT_MIN, 5));
$oField->addValidator(new Validator(Validator::TYPE_INT_MAX, 10));

……反正我就是这么干的。

于 2012-04-26T11:03:41.917 回答