Codeigniter 的正则表达式匹配 [英] Codeigniter's regex match
问题描述
我有这个正则表达式用于 javascript 中的验证:
I have this regular expression for validation in javascript:
/^(?:'[A-z](([._-][A-z0-9])|[A-z0-9])*[a-z0-9_]*')$/
现在我想要使用 Codeigniter 的表单验证进行表单验证的相同正则表达式:
Now I want the same regular expression for the form validation using Codeigniter's form validation:
$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]');
该行中的正则表达式与我提到的不同.
the regex in that line is not equivalent to the one I mentioned.
尝试复制和粘贴相同的正则表达式时,它不起作用.我知道这很愚蠢,我似乎无法完全理解正则表达式.
When trying to copy and paste same regex, It doesn't work. I know this is dumb i just can't seem to fully understand regular expressions.
推荐答案
虽然有没有 regex_match()
CodeIgniter 中的方法 验证库,CI用户指南中没有列出.
Though there is no regex_match()
method in CodeIgniter validation library, It's not listed in the CI User Guide.
根据 @Limon 的评论:
CodeIgniter 中有一个带有管道 |
的错误,它破坏了正则表达式.
There is a bug in CodeIgniter with the pipe
|
, it breaks the regex.
CodeIgniter 使用|
作为验证方法之间的分隔符.
CodeIgniter uses |
as a separator between validate methods.
因此,为了防止破坏正则表达式,您可以创建一个 控制器中的回调方法通过匹配正则表达式来验证输入:
Therefore, to prevent from breaking the regex, you could create a callback method in your Controller to validate the input by matching the regex:
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;
}
}
然后添加验证规则,如下:
Then add the validation rule, as follows:
$this->form_validation->set_rules('username', 'Nombre de usuario', 'required|min_length[2]|max_length[15]|callback_regex_check|is_unique[user.username]');
这篇关于Codeigniter 的正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!