1

I have made a custom rule to validate mobile no. with specific pattern and requirement.

Pattern [0-9]{3}-[0-9]{4}-[0-9]{4}

The first three digits should be one of the following numbers:

010, 020, 030, 040, 050, 060, 070, 080, 090

Below is my code for custom rule.

App/Rules/MobileNumber.php

    public function passes($attribute, $value)
    {
        $pattern  = "/^\[0-9]{4}-[0-9]{4}-[0-9]{3}$/";
        return preg_match($pattern, $value);
    }

My custom validator:

app/HTTP/Request/UserRequest.php

    use App\Rules\MobileNumber;
    ......
    //manipulate data before validation
    public function validationData()
    {
            $this->merge([
            'tel_number' =>  $this->tel_number_1.'-'. $this->tel_number_2.'-'.$this->tel_number_3,
        ]);
    }

    public function rules()
    {
        return [
            //other rules here....
            'mob_number' => 'required', new MobileNumber()
        ];
    }

But with the above code the validation is not working.tel_number is not reaching to passes method to check for validation. I.E If user gives alphabetic char or symbols they are being forwarded for database save method.

So I cannot check if my regex is correct or not.

It would be very helpful if someone could highlight the mistake I've made here. Also confirm if my regex is correct to pass the validation.

3
  • Can you show some full examples of what should pass? Commented Apr 13, 2022 at 17:30
  • 2
    [0-9]{3} would allow 0-9 for the first 3 digits, like 111, 278, 991, etc. If you want the 1st and 3rd digit to explictly be 0, and the 2nd to be 1-9 you would probably need something like 0[1-9]0-[0-9]{4}-[0-9]{4} Commented Apr 13, 2022 at 17:30
  • 2
    You should not escape \[ The pattern can be written as $pattern = "/^0[1-9]0-\d{4}-\d{4}$/"; see regex101.com/r/wo65hK/1 Commented Apr 13, 2022 at 17:30

1 Answer 1

1

I can only answer the last point for the regex validation.

You switched the order in the implementation to 4-4-3 instead of 3-4-4 digits.

The sequences 010, 020, 030, 040, 050, 060, 070, 080, 090 can be matched using 0[1-9]0 and you should not escape the \[ or else you will match it literally.

The updated code might look like:

$pattern  = "/^0[1-9]0-\d{4}-\d{4}$/";
Sign up to request clarification or add additional context in comments.

Comments

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.