工作正则表达式在 laravel 验证中不起作用
Posted
技术标签:
【中文标题】工作正则表达式在 laravel 验证中不起作用【英文标题】:Working regex not work in laravel validation 【发布时间】:2019-03-28 17:19:59 【问题描述】:我有自定义正则表达式用于验证社交网站中的用户个人资料网址:
/(?:https:\/\/)?(?:http:\/\/)?(?:www\.)?(?:ok|odnoklassniki)\.ru\/(?:\w*#!\/)?([\w-]*)/
查看演示here。
代码:
if(isset($request->odnoklassniki))
$this->validate($request, [
'odnoklassniki' => 'regex:/(?:https:\/\/)?(?:http:\/\/)?(?:www\.)?(?:ok|odnoklassniki)\.ru\/(?:\w*#!\/)?([\w-]*)?/'
], ['regex' => 'Enter correct url to your profile in this website']);
$candidate->odnoklassniki = $request->odnoklassniki;
$candidate->save();
错误信息:
preg_match(): 没有找到结束分隔符'/'
正则表达式在我的 php 代码中成功运行:
$re = '/(?:https:\/\/)?(?:http:\/\/)?(?:www\.)?(?:ok|odnoklassniki)\.ru\/(?:\w*#!\/)?([\w-]*)/m';
$str = 'https://www.odnoklassniki.ru/username
http://odnoklassniki.ru/username
ok.ru/username
';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
echo "<pre>";
print_r($matches);
echo "</pre>";
结果:
Array
(
[0] => Array
(
[0] => https://www.odnoklassniki.ru/username
[1] => username
)
[1] => Array
(
[0] => http://odnoklassniki.ru/username
[1] => username
)
[2] => Array
(
[0] => ok.ru/username
[1] => username
)
)
【问题讨论】:
【参考方案1】:管道字符“|”在验证中有特殊作用,它分隔你的验证规则,例如:
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255'
]);
但由于您的正则表达式验证包含管道字符,您可以使用其他方法声明验证规则
$validatedData = $request->validate([
'title' => [
'required',
'unique:posts',
'max:255'
]
]);
所以这就是你的问题的解决方案:
if(isset($request->odnoklassniki))
$this->validate($request, [
'odnoklassniki' => [
'regex:/(?:https:\/\/)?(?:http:\/\/)?(?:www\.)?(?:ok|odnoklassniki)\.ru\/(?:\w*#!\/)?([\w-]*)?/'
]
], ['regex' => 'Enter correct url to your profile in this website']);
$candidate->odnoklassniki = $request->odnoklassniki;
$candidate->save();
【讨论】:
谢谢,@aceraven777以上是关于工作正则表达式在 laravel 验证中不起作用的主要内容,如果未能解决你的问题,请参考以下文章