Use Laravel 5.5 Rule Object to validate the Pincode

When you develop a web application, you have to create custom validation rules for validating certain business logic. Laravel 5.5 makes the creating the custom validation rules very easy.

Laravel 5.5 introduced a new Artisan command for making the validation rule class.

php artisan make:rule ValidPinCode

The above command will generate a new class “ValidPinCode” in “app/Rules” folder, this is where Laravel keeps all the custom validation rules classes.

Let’s open the file to see what is inside.

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class ValidPinCode 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)
    {
        //
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The validation error message.';
    }
}

You can see “ValidPinCode” class implements the “Rule” contract.

If you are curious about how the “Rule” contract looks like, lets open that file Rule.php located at “vendor/laravel/framework/src/Illuminate/Contracts/Validation”.

<?php

namespace Illuminate\Contracts\Validation;

interface Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value);

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message();
}

The interface Rule has only two methods — passes and message. The passes method should return true or false depending on whether the attribute value is valid or not. The message method should return the validation error message that should be used when validation fails.

Add an additional text box in user registration form (register.blade.php) for the pin code. In this tutorial, we assume the user should enter their pin code while signup. So we have to make sure that, the pin code is valid before we save the user details into the database.

We will use the API http://postalpincode.in/Api-Details for validating the pin code.

Make sure you install Guzzle package via composer because we will use the Guzzle HTTP client to make the API request.

"guzzlehttp/guzzle": "~5.3|~6.0"

The complete code for ValidPinCode.php

<?php

namespace App\Rules;

use GuzzleHttp\Client;
use Illuminate\Contracts\Validation\Rule;

class ValidPinCode implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $client = new Client();
        $url = 'http://postalpincode.in/api/pincode/' . $value;
        $body = json_decode($client->get($url)->getBody());
        if($body->Status == 'Error') {
           return false;
        }
        return true;
    }

     /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Pincode is not valid.';
    }
}

Now you can use the rule object ‘ValidPinCode’ in RegisterController as below

protected function validator(array $data)
{
   return Validator::make($data, [
      'name' => 'required|string|max:255',
      'email' => 'required|string|email|max:255|unique:users',
      'password' => 'required|string|min:6|confirmed',
      'pincode' => [
         'required',
          new ValidPinCode
       ]
   ]);
}

Originally published on Medium

About Author

Kiran Krishnan

Co-founder @ Cedex Technologies LLP | Helping businesses turn their product ideas into reality.

Want to work with us?

Send us your requirements. We will get back to you with a free quote.