Laravel 5.6验证正则表达式为空字符串

问题描述 投票:0回答:1

我想用Validator检查电话串。代码在上面。

$rules = [
    'phone' => 'regex:/^09\d{8}$/'
];
$messages = [
    'phone.regex' => 'INVALID_PHONE',
];

测试1:

$data = [
    'phone' => 'test'
];
$vali = Validator::make($data, $rules, $messages);

dd($vali->errors()->first()); // I got "INVALID_PHONE". That's I exactly expected.

测试2:

$data = [
    'phone' => ''
];
$vali = Validator::make($data, $rules, $messages);

dd($vali->errors()->first()); // I got "". I expected it is "INVALID_PHONE"

我错过了什么?

我只想使用正则表达式。

php regex laravel validation
1个回答
3
投票

这是因为它也需要它;

$rules = [
    'phone' => 'required|regex:/^09\d{8}$/'
];

当您传递一个空字符串时,验证通过,因为不需要电话字段,因为它是空的,它不会检查正则表达式。一旦它不是空字段,它将检查正则表达式模式

© www.soinside.com 2019 - 2024. All rights reserved.