Codeigniter表单验证.阿尔法和空间

khe*_*duk 9 codeigniter

使用Codeigniter表单验证时,alpha是否允许空格?防爆."鲍勃史密斯"

You*_*sef 17

这是一个应该解决您的问题的代码:

function alpha_dash_space($str)
{
    return ( ! preg_match("/^([-a-z_ ])+$/i", $str)) ? FALSE : TRUE;
} 
Run Code Online (Sandbox Code Playgroud)

在规则中,您可以像下面这样调用它:

$this->form_validation->set_rules('name', 'Name', trim|xss_clean|callback_alpha_dash_space');
Run Code Online (Sandbox Code Playgroud)

编辑

从callback_alpha_dash_space中删除了一个额外的_


Jee*_*eva 7

我知道我迟到了回答这个问题.但对于那些仍在寻找如何只允许字母和空格的答案的人,你可以遵循:

在表单验证中

$this->form_validation->set_rules('fullname', 'Fullname', 'min_length[7]|trim|required|xss_clean|callback_alpha_dash_space');
Run Code Online (Sandbox Code Playgroud)

然后为alpha_dash_space添加回调函数

function alpha_dash_space($fullname){
    if (! preg_match('/^[a-zA-Z\s]+$/', $fullname)) {
        $this->form_validation->set_message('alpha_dash_space', 'The %s field may only contain alpha characters & White spaces');
        return FALSE;
    } else {
        return TRUE;
    }
}
Run Code Online (Sandbox Code Playgroud)
  • ^$告诉它它是字符串的开头和结尾
  • a-z是小写字母,A-Z是大写字母
  • \s是空格,+意思是1次或更多次.

希望它有所帮助!


小智 5

不,它不允许空格.

有人写了一个库扩展,但允许这样做:http://ellislab.com/forums/viewthread/158696/#794699