2015-06-26 62 views
3

在我的视图页面中。我有一个用于输入注释的文本框。在我的代码验证 中只允许使用alpha。如何在代码验证中允许空格,逗号,点号和字母表

我需要留出空间,逗号,句号,连字符注释字段.. 怎么这个地方我验证组规则

$this->form_validation->set_rules('e_comment', 'Comments', 'required|alpha'); 
+0

如何设置一个回调函数来允许这些事情..? – robins

+1

使用回调函数,通过正则表达式检查输入 –

+0

谢谢你的朋友 – robins

回答

4

要你将需要使用callback功能自定义验证。

// validation rule 
$this->form_validation->set_rules('comment', 'Comments', 'required|callback_customAlpha'); 

// callback function 
public function customAlpha($str) 
{ 
    if (!preg_match('/^[a-z .,\-]+$/i',$str)) 
    { 
     return false; 
    } 
} 

// custom error message 
$this->form_validation->set_message('customAlpha', 'error message'); 
+0

非常感谢你..让我所有的需要 – robins

+0

这个作品。但是,即使字段为空并且不需要,它也会在提交时返回错误消息。怎么样? – Jorz

0
function alpha($str) 
{ 
    return (! preg_match("/^([-a-z_ ])+$/i", $str)) ? FALSE : TRUE; 
} 

在规则,你可以把它像如下:

$this->form_validation->set_rules('comment', 'Comments', required|callback_alpha'); 

编辑01

return (! preg_match("/^([-a-z_ .,\])+$/i", $str)) ? FALSE : TRUE; 

更改此

+0

此代码正在工作,但它不允许逗号,点 – robins

+0

答案更新 –

+0

我该如何防止|性格? – robins

0

容易和最佳办法做到这一点,

转到system/library/form_validation.
并进行功能或扩展库:

public function myAlpha($string) 
    { 
     if (!preg_match('/^[a-z .,\-]+$/i',$string)) 
     { 
      return false; 
     } 
    } 

现在,你想让它正常使用。

$this->form_validation->set_rules('comment', 'Comments', 'required|myAlpha'); 
相关问题