在我的视图页面中。我有一个用于输入评论的文本框。在我的代码点火器验证中只允许alpha。
我需要在"注释"字段中允许空格、逗号、点和连字符。。这个地方在我的验证集中是如何规则的
$this->form_validation->set_rules('e_comment', 'Comments', 'required|alpha');
要进行自定义验证,需要使用回调函数。
// 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');
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;
更改此
简单且最佳的方法,
转到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');
由于我没有足够的声誉来评论另一个答案,我将添加jeemusu的这个改进答案,以包括jorz提出的问题,这是为了避免在输入的数据为空时引发错误消息
// 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)&& $str!= "" )
{
return false;
}
}
// custom error message
$this->form_validation->set_message('customAlpha', 'error message');