Create Custom Form Validation Rules in Laravel – Validate using API

All of us are aware that Laravel provides a very convenient way of validating forms using form validation. But did you ever find yourself needing to validate a form field using a third-party API? I just hit this requirement recently in a project.
So basically I was saving an API key for a third-party service and was required to validate whether the API key was valid.
I already had the `FormRequest` class created to validate the request. But it does not allow me to validate data against a third-party API. So I thought of creating a custom validation rule where I could send an API request to the API and validate the response.
Here is what I did:

1. Create the custom validation rule

php artisan make:rule ApiTokenRule

2. Add custom rule to the ApiTokenRule class.

This class makes a request to our third party API with the token that we want to validate. This logic is written inside the passes function of our rule class. If we receive the ok response, it means our token is correct and validation is passed. Otherwise, the validation fails.

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Http;

class ApiTokenRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct() {}

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        // Call the API URL
        $response = Http::withToken($value)->post('https://myapi.url/endpoint');

        // If the API retuned the correct response, validation is passed
        if ($response->ok()) {
            return true;
        }

        return false;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The API key seems to be invalid.';
    }
}

3. Add the custom rule to FormRequest

The custom rule we created above, should be added to the validation rules for the form request. If we have the FormRequest class available, add the custom rule to rules() function as below:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Rules\ApiTokenRule;

class StoreCompanyRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => ['required', 'max:255'],
            'email' => ['required', 'email:rfc'],
            'api_key' => ['required', new ApiTokenRule()]
        ];
    }
}
?>

In the above code, the api_key field will be validated against our custom rule every time the form is saved.

Written by Arvind Bhardwaj

Arvind is a certified Magento 2 expert with more than 10 years of industry-wide experience.

Website: http://www.webspeaks.in/