首页 > 解决方案 > 如何使用 Validation Laravel 排除字符串中的电话号码和 URL?

问题描述

我想验证一个不包含电话号码或网址的“标题”字段。我已经尝试过使用正则表达式,它只有在我单独输入电话号码或 url 时才有效

举个例子:

0617859654 --> 工作,验证失败

测试 0617859654 -> 不工作,验证未检测到电话号码

这是我的代码:

$validator = Validator::make($request->all(), [
            'titre' => 'not_regex:/^([0-9\s\-\+\(\)]*)$/|not_regex:/^https:\/\/\w+(\.\w+)*(:[0-9]+)?\/?$/|not_regex:/^http:\/\/\w+(\.\w+)*(:[0-9]+)?\/?$/',
        ]);

因此验证不能完全起作用,如果电话号码或 url 在我的标题字段中,我如何阻止验证?

谢谢 !

标签: phplaravelvalidationlaravel-5

解决方案


我解决这个问题的方法是在给定的字符串中找到匹配的模式。我没有确切的解决方案,但 PHP 有一个名为Preg_match()preg_match_all()的方法

首先在这些方法中传递您的标题,它将返回 True 或 false 甚至匹配的模式。

preg_match ( string $pattern , string $subject , array &$matches = null , int $flags = 0 , int $offset = 0 ) : int|false

或者

preg_match_all ( string $pattern , string $subject , array &$matches = null , int $flags = 0 , int $offset = 0 ) : int|false|null

阅读更多:https ://www.php.net/manual/en/function.preg-match.php

希望你能明白。谢谢


推荐阅读