Codeigniter的正则表达式匹配

Lim*_*mon 3 php regex validation codeigniter

我有这个正则表达式在javascript验证:

/^(?:'[A-z](([\._\-][A-z0-9])|[A-z0-9])*[a-z0-9_]*')$/
Run Code Online (Sandbox Code Playgroud)

现在,我希望使用Codeigniter的表单验证进行表单验证的相同正则表达式:

$this->form_validation->set_rules('username', 'Nombre de usuario', 'required|min_length[2]|max_length[15]|regex_match[/^[A-Z a-z 0-9 _ . \-]+$/]|is_unique[user.username]');
Run Code Online (Sandbox Code Playgroud)

该行中的正则表达式与我提到的正则表达式不同.

当试图复制和粘贴相同的正则表达式时,它不起作用.我知道这是愚蠢的我似乎无法完全理解正则表达式.

Has*_*ami 5

虽然CodeIgniter 验证库中没有 regex_match()方法,但CI用户指南中未列出该方法.

Per @Limon的评论:

CodeIgniter中有一个带有管道的错误|,它打破了正则表达式.

使用|作为验证方法之间的隔板.

因此,为了防止破坏正则表达式,您可以在Controller中创建一个回调方法,通过匹配正则表达式来验证输入:

public function regex_check($str)
{
    if (preg_match("/^(?:'[A-Za-z](([\._\-][A-Za-z0-9])|[A-Za-z0-9])*[a-z0-9_]*')$/", $str))
    {
        $this->form_validation->set_message('regex_check', 'The %s field is not valid!');
        return FALSE;
    }
    else
    {
        return TRUE;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后添加验证规则,如下所示:

$this->form_validation->set_rules('username', 'Nombre de usuario', 'required|min_length[2]|max_length[15]|callback_regex_check|is_unique[user.username]');
Run Code Online (Sandbox Code Playgroud)