将自定义回调添加到Codeigniter表单验证

shi*_*hin 6 php validation codeigniter

我想用@ mywork.com限制我的电子邮件注册我在My_Form_validation中做了以下内容.

public function email_check($email)
    {
        $findme='mywork.com';
        $pos = strpos($email,$findme);
        if ($pos===FALSE)
        {
            $this->CI->form_validation->set_message('email_check', "The %s field does not have our email.");
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我用它如下.我对用户名和密码使用CI规则,它适用于电子邮件,它接受任何电子邮件地址.任何我感谢任何帮助.

function register_form($container)
    {
....
....

/ Set Rules
$config = array(
...//for username
// for email            
    array(
  'field'=>'email',
  'label'=>$this->CI->lang->line('userlib_email'),
  'rules'=>"trim|required|max_length[254]|valid_email|callback_email_check|callback_spare_email"
   ),
...// for password
 );

$this->CI->form_validation->set_rules($config);
Run Code Online (Sandbox Code Playgroud)

Jor*_*eno 17

直接在控制器中创建回调的问题是,现在可以通过调用http://localhost/yourapp/yourcontroller/yourcallback来访问它,这是不可取的.有一种更加模块化的方法可以将验证规则放入配置文件中.我建议:

你的控制器:

<?php
class Your_Controller extends CI_Controller{
    function submit_signup(){
        $this->load->library('form_validation');
        if(!$this->form_validation->run('submit_signup')){
            //error
        }
        else{
            $p = $this->input->post();
            //insert $p into database....
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

application/config/form_validation.php:

<?php
$config = array
(   
    //this array key matches what you passed into run()
    'submit_signup' => array
    (
        array(
            'field' => 'email',
            'label' => 'Email',
            'rules' => 'required|max_length[255]|valid_email|belongstowork'
        )
        /*
        ,
        array(
            ...
        )
        */

    )
    //you would add more run() routines here, for separate form submissions.
);
Run Code Online (Sandbox Code Playgroud)

application/libraries/MY_Form_validation.php:

<?php
class MY_Form_validation extends CI_Form_validation{    
     function __construct($config = array()){
          parent::__construct($config);
     }
     function belongstowork($email){
         $endsWith = "@mywork.com";
         //see: http://stackoverflow.com/a/619725/568884
         return substr_compare($endsWith, $email, -strlen($email), strlen($email)) === 0;
     }
}
Run Code Online (Sandbox Code Playgroud)

application/language/english/form_validation_lang.php:

加: $lang['belongstowork'] = "Sorry, the email must belong to work.";