2011-11-22 49 views
8

有人可以提供一些建议,如何去为Codeigniter创建自定义验证规则。Codeigniter自定义电子邮件验证规则

我工作的网站是给大学生的,只允许用户注册他们是否使用他们的大学邮件地址。

这里是验证我想实现的类型的例子:

仅允许与结尾的电子邮件:

array(
    '0' => '@uni-email-1.com', 
    '1' => '@uni-email-2.com', 
    '2' => '@uni-email-3.com', 
    '3' => '@uni-email-4.com', 
); 

我还是很新的笨,我不知道如何来创建这种类型的验证。

任何援助非常感谢!

谢谢

回答

11

当然,这是怎么回事?

function index() 
{ 
    $this->load->helper(array('form', 'url')); 

    $this->load->library('form_validation'); 


    $this->form_validation->set_rules('email', 'Email', 'required'); 
    $this->form_validation->set_rules('email', 'Email', 'valid_email'); 
    $this->form_validation->set_rules('email', 'Email', 'callback_email_check'); 

    if ($this->form_validation->run() == FALSE) 
    { 
     //fail 
    } 
    else 
    { 
     //success 
    } 
} 

function email_check($str) 
{ 

    if (stristr($str,'@uni-email-1.com') !== false) return true; 
    if (stristr($str,'@uni-email-2.com') !== false) return true; 
    if (stristr($str,'@uni-email-3.com') !== false) return true; 

     $this->form_validation->set_message('email', 'Please provide an acceptable email address.'); 
     return FALSE; 

} 
+0

这工作完美!谢谢你的时间。 – RipzCurlz

1

这实际上比CI更相关的PHP。基本上,您应该将插入的电子邮件地址与您提供的每个结束字符串匹配。如果有匹配 - 允许注册,如果没有 - 输出警报或其他内容,并且不允许。

1

如果你的大学有一个LDAP目录,那么你可以对它进行身份验证,而不是拥有另一个基础。单点登录是机构在使用时非常优秀的系统,比如大学

1

尝试类似以下,

$formatArr = array("@uni-email-1.com", "@uni-email-2.com" "@uni-email-3.com"); 

$this->form_validation->set_rules('email', 'Email', 'callback__check_email'); 

//then the validation function 
function _check_email() { 
    $email = $this->input->post("email"); 
    $emailLastPart = array_pop(explode("@", $email)); 
    if(!in_array($emailLastPart, $formatArr)) { 
     $this->form_validation->set_message('email', 'Please provide valid email address.'); 
     return FALSE; 
    } 
    return TRUE; 
} 

希望它可以帮助

+0

感谢您的时间和意见,但是我无法获得此代码的工作。 – RipzCurlz

4
public function index() 
    { 
     $this->load->helper(array('form', 'url')); 

     $this->load->library('form_validation'); 

     $this->form_validation->set_rules('email', 'Email', 'required|callback_email_check'); 

     if ($this->form_validation->run() == FALSE) 
     { 
      $this->load->view('form'); 
     } 
     else 
     { 
      $this->load->view('formsuccess'); 
     } 
    } 

    public function email_check($email) 
    { 
     if(stristr($str,'@uni-email-1.com') !== false) return true; 
     if(stristr($str,'@uni-email-2.com') !== false) return true; 
     if(stristr($str,'@uni-email-3.com') !== false) return true; 

     $this->form_validation->set_message('email', 'Please provide an acceptable email address.'); 
     return FALSE; 
    } 
0

您可以通过HTML5简单的代码

验证电子邮件

带图案