0

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.

2
  • My fault, simon's right, i misread your requirement Commented Sep 5, 2018 at 21:22
  • "$errors->errors()" Like "MessageBag{ #message: [] }" Commented Sep 5, 2018 at 21:23

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

6 Comments

That's working! Thank you. But I still want to know why regex is not working.
How is it not working? Is it not working because when you type 0900000000 it still errors or because you need the required param?
I expect the string like 0900000000 But why empty string is passed
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 empy field it will check the regex pattern.
Thank you for the explanation. Now I understand !!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.