在php中输入验证

时间:2012-04-26 10:20:23

标签: php validation

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做类似的工作?我的意思是验证

2 个答案:

答案 0 :(得分:0)

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

这些应该让你开始,其余的have a look at how codeigniter does themarticle on server side validation with php

希望这有帮助!

答案 1 :(得分: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()查询)或其他任何东西,你只是为特定情况构建Validator类型......或者你有通用验证器:

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()方法都循环遍历所有附加字段,检查它们是否具有Validators,如果是,则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));

......无论如何,我就是这样做的。