How to only accept international format (E.164) for a specific country?
mohdalali opened this issue · 2 comments
mohdalali commented
I want to accept international phone number format for only numbers from UAE, using the Propaganistas / Laravel-Phone package.
I tried using the below code snippet, but it allows any international phone number + local phone number from AE.
'phonefield' => 'phone:INTERNATIONAL,AE',
So with this, it accepts all countries' phone numbers in international format + it will also accept local phone numbers from UAE. However, I want to only accept international format of UAE numbers, how can I do that?
mohdalali commented
I did this, is this right?
$input_phone = $data['username'];
$phone = new PhoneNumber($input_phone);
if (!$phone->isValid() || !$phone->isOfCountry('AE'))
return response()->error(null, __('validation.phone', ['attribute' => 'phone']), Response::HTTP_BAD_REQUEST);
$data['username'] = $phone->formatE164();
Propaganistas commented
You could add a closure validation rule (basic Laravel functionality) for checking the format:
$rules = [
'phonefield' => [
'phone:AE', // Checks the origin of the number.
function (string $attribute, mixed $value, \Closure $fail) { // Checks the E164 format.
$expected_value = phone($value, 'AE')->formatE164();
if ($value !== $expected_value) {
$fail("The {$attribute} should be provided in E164 format.");
}
},
],
];