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.
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}$/";