Skip to content

Instantly share code, notes, and snippets.

@grandmanitou
Created June 10, 2020 11:58
Show Gist options
  • Save grandmanitou/dfeeb7bdbc0d27fdea592d63c0898a3e to your computer and use it in GitHub Desktop.
Save grandmanitou/dfeeb7bdbc0d27fdea592d63c0898a3e to your computer and use it in GitHub Desktop.
Laravel phone number (all types) custom validation rule class
<?php
namespace App\Http\Requests;
use App\Rules\PhoneNumber;
use Illuminate\Foundation\Http\FormRequest;
use libphonenumber\PhoneNumberType;
class ContactRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'company_id' => 'nullable',
'first_name' => 'nullable',
'last_name' => 'nullable',
'email' => 'required|email',
'fixed_phone' => ['nullable', new PhoneNumber(PhoneNumberType::FIXED_LINE)],
'mobile_phone' => ['nullable', new PhoneNumber(PhoneNumberType::MOBILE)],
'job_title' => 'nullable',
];
}
}
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use libphonenumber\NumberParseException;
use libphonenumber\PhoneNumberUtil;
class PhoneNumber implements Rule
{
private $phoneNumberUtil;
private $phoneNumberType;
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct($phoneNumberType = null)
{
$this->phoneNumberType = $phoneNumberType;
$this->phoneNumberUtil = PhoneNumberUtil::getInstance();
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
try {
$phoneNumberObject = $this->phoneNumberUtil->parse($value);
} catch (NumberParseException $e) {
return false;
}
// Is it a valid number?
if ($this->phoneNumberUtil->isValidNumber($phoneNumberObject)) {
// If type is provided, is it valid?
if ($this->phoneNumberType) {
$phoneNumberType = $this->phoneNumberUtil->getNumberType($phoneNumberObject);
if ($this->phoneNumberType == $phoneNumberType) {
return true;
}
return false;
}
return true;
}
return false;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return __('The :attribute is not a valid phone number.');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment