Evan
Evan

Reputation: 3

Laravel 5.6 Validation Regex for empty string

I want to check phone string with Validator. The code is above.

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

Test 1:

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

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

Test 2:

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

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

What I missing?

I want to use only regex.

Upvotes: 0

Views: 315

Answers (1)

Simon R
Simon R

Reputation: 3772

It's because it needs to be required as well;

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

When you pass an empty string the validation passes because the phone field is not required so because it's empty it does not check the regex. As soon as it's not an empty field it will check the regex pattern

Upvotes: 3

Related Questions