Codeigniter的正则表达式匹配 [英] Codeigniter's regex match
问题描述
我有这个正则表达式在javascript中验证:
/ ^(?:'[Az] \\._\ - ] [A-z0-9])| [A-z0-9])* [a-z0-9 _] *')$ /
pre>
现在我想要使用Codeigniter的表单验证的表单验证的同一个正则表达式:
$ this-> form_validation-> set_rules('username','Nombre de usuario','required | min_length [2] | max_length [15] | regex_match [/ ^ _。\ - ] + $ /] | is_unique [user.username]');
该行中的正则表达式不等同于我提到的正则表达式。
尝试复制和粘贴同一个正则表达式时,它不工作。我知道这是蠢,我似乎不能完全理解正则表达式。
解决方案虽然没有
regex_match()
method in CodeIgniter 验证库,它未列在CI中用户指南。
根据 @Limon 的评论:
在CodeIgniter中有一个管道
|
,它会破坏正则表达式。
CodeIgniter 使用
|
作为validate方法之间的分隔符。
因此,为了防止破坏正则表达式,您可以创建一个回调方法,通过匹配regex验证输入:
public函数regex_check($ str)
{
if(1!== preg_match(/ ^(?:'[A-Za-z](([\._\-] [A -Za-z0-9])| [A-Za-z0-9])* [a-z0-9 _] *')$ /,$ str))
{
$ this- > form_validation-> set_message('regex_check','%s字段无效!');
return FALSE;
}
else
{
return TRUE;
}
}
然后添加验证规则,如下所示: p>
$ this-> form_validation-> set_rules('username','Nombre de usuario', 'required | min_length [2] | max_length [15] | callback_regex_check | is_unique [user.username]');
I have this regular expression for validation in javascript:
/^(?:'[A-z](([\._\-][A-z0-9])|[A-z0-9])*[a-z0-9_]*')$/
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.
解决方案Though there is
noregex_match()
method in CodeIgniter validation library, It's not listed in the CI User Guide.Per @Limon's comment:
There is a bug in CodeIgniter with the pipe
|
, it breaks the regex.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 (1 !== 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屋!