在我的视图页面中。我有一个用于输入评论的文本框。在我的codeigniter验证中 只允许使用alpha。
我需要在Comment字段中允许空格,逗号,点,连字符。 我的验证集规则中的这个位置
AccesssibilityNodeInfo
答案 0 :(得分: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');
答案 1 :(得分: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;
更改此
答案 2 :(得分: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');
答案 3 :(得分:0)
由于我没有足够的声誉来评论另一个答案,因此我将添加对此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');