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.
[0-9]{3}would allow 0-9 for the first 3 digits, like111,278,991, etc. If you want the 1st and 3rd digit to explictly be0, and the 2nd to be 1-9 you would probably need something like0[1-9]0-[0-9]{4}-[0-9]{4}\[The pattern can be written as$pattern = "/^0[1-9]0-\d{4}-\d{4}$/";see regex101.com/r/wo65hK/1