DEV Community

Cover image for Phone Validation in Laravel Using Abstract
Yoram Kornatzky
Yoram Kornatzky

Posted on

Phone Validation in Laravel Using Abstract

Our sales events platform Auctibles, collects phone numbers for several purposes:

  1. Contact phone of sellers to be displayed to buyers
  2. Landline phone of sellers
  3. Mobile phone of sellers for coordination of deliveries
  4. Mobile phone of buyers for coordination of deliveries

Phone validation in Laravel is a crucial step for our sales events platform. It plays a significant role in ensuring smooth delivery coordination and reducing the risk of fraud.

We use validation rules, a practical feature of the PHP Laravel framework, to ensure reliable validation. This is where the Abstract comes in, enhancing the functionality of our platform.

The Validation Rule

We define a validation rule, AbstractPhoneValidation that receives two parameters:

  1. The type of phone number expected - mobile, landline, or an empty string when any type is expected,
  2. The country of the phone number - two letters ISO 3166-1 alpha-2 code

The rule uses our Abstract API key from the configuration file.

    namespace App\Rules;

    use Closure;
    use Illuminate\Contracts\Validation\ValidationRule;
    use Illuminate\Support\Str;

    class AbstractPhoneValidation implements ValidationRule
    {
        /**
         * Create a new rule instance.
         *
         * @return void
         */
        public function __construct(
            private string $phone_type,
            private string $country,
        ) {}    


        /**
         * Run the validation rule.
         *
         * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
         */
        public function validate(string $attribute, mixed $value, Closure $fail): void
        {
            // Initialize cURL.
            $ch = curl_init();

            // Set the URL that you want to GET by using the CURLOPT_URL option.
            curl_setopt(
              $ch,
              CURLOPT_URL,
              'https://phonevalidation.abstractapi.com/v1/?api_key=' . config('app.ABSTRACT_PHONE_VERIFICATION_KEY') . "&phone=$value"
            );

            // Set CURLOPT_RETURNTRANSFER so that the content is returned as a variable.
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Set CURLOPT_FOLLOWLOCATION to true to follow redirects.
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

            // Execute the request.
            $data = curl_exec($ch);

            // Close the cURL handle.
            curl_close($ch);

                    //The response from Abstract is a JSON
            $data = json_decode($data);

                    // here, we do the validation
            if (!$data->valid || 
                // Is the phone number valid?
                ($this->phone_type && Str::lower($data->type) != $this->phone_type) || 
                // If the phone type was given, what the phone number of the required type?
                ($data->country->code != $this->country)
                // Does the country of the phone correspond to the expected country?
            ) 
                    {
                $fail('validation.' . $attribute)->translate();
            }

        }
    }
Enter fullscreen mode Exit fullscreen mode

As Abstract returns the phone type capitalized, we use Str::lower to convert it to lowercase to correspond to our labeling of phone types.

Using the Validation Rule

We use the rule in validation, where the user's country two letters ISO 3166-1 alpha-2 code is stored in $country:

$rules_array = [
    'mobile_phone' => [new AbstractPhoneValidation('mobile', $country)],
    'landline_phone' => [new AbstractPhoneValidation('landline', $country)],
    'contact_phone' => [new AbstractPhoneValidation('', $this->country)],
]);
Enter fullscreen mode Exit fullscreen mode

For a contact_phone, any type of phone number is acceptable.

Top comments (0)