Laravel如何编写忽略手机号空格并拦截指定号码的验证规则?
你之前的方案失效是因为Rule::notIn只会直接匹配原始输入的完整字符串,不会自动处理输入里的空格,所以带空格的变体号码无法被拦截。同时原规则中的number验证规则会拦截带空格的输入,不符合你允许手机号内保留空格的需求,需要替换为string规则。
解决方案
方案1:闭包验证(最简便,无需额外定义类)
直接在验证规则中添加处理逻辑,移除所有空格后再判断是否为禁用号码:
'number' => [ 'required', 'string', function ($attribute, $value, $fail) { $strippedValue = str_replace(' ', '', $value); if ($strippedValue === '07911123456') { $fail('该手机号为禁止使用的号码'); } } ],
方案2:正则匹配方案
如果偏好使用正则规则实现,可用not_regex拦截所有数字顺序匹配、中间带任意空格的号码:
'number' => [ 'required', 'string', 'not_regex:/^0\s*7\s*9\s*1\s*1\s*1\s*2\s*3\s*4\s*5\s*6\s*$/' ],
方案3:可复用自定义规则
如果多处业务需要用到该验证逻辑,可生成独立的验证规则类:
- 执行命令生成规则类:
php artisan make:rule DisabledPhone - 编辑
app/Rules/DisabledPhone.php文件:
public function passes($attribute, $value) { $strippedValue = str_replace(' ', '', $value); return $strippedValue !== '07911123456'; } public function message() { return '该手机号为禁止使用的号码'; }
- 在验证规则中调用:
'number' => ['required', 'string', new \App\Rules\DisabledPhone()],
内容的提问来源于stack exchange,提问作者OnlyProblems
相关产品推荐
相关产品推荐

