我想通过@ 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;
}
}
我按如下方式使用它。我对用户名和密码使用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);
答案 0 :(得分: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....
}
}
}
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.
);
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;
}
}
application/language/english/form_validation_lang.php
添加:$lang['belongstowork'] = "Sorry, the email must belong to work.";
答案 1 :(得分:0)
您是否需要在Codeigniter回调函数中进行类似的验证?
$this->form_validation->set_rules('email', 'email', 'trim|required|max_length[254]|valid_email|xss_clean|callback_spare_email[' . $this->input->post('email') . ']');
if ($this->form_validation->run() == FALSE)
{
// failed
echo 'FAIL';
}
else
{
// success
echo 'GOOD';
}
function spare_email($str)
{
// if first_item and second_item are equal
if(stristr($str, '@mywork.com') !== FALSE)
{
// success
return $str;
}
else
{
// set error message
$this->form_validation->set_message('spare_email', 'No match');
// return fail
return FALSE;
}
}
答案 2 :(得分:0)
对Jordan的答案进行更正,您需要编辑的语言文件应位于
<强>系统/语言/英语/ form_validation_lang.php 强>
不是申请/.../ form_validation_lang.php。如果在具有相同名称的应用程序路径下创建新文件,它将覆盖系统路径中的原始文件。因此,您将失去原始过滤器的所有用法。