Laravel Credit Card Validation
Tags: php, laravel, webdev, security
Published: 2021-01-09 10:15:12

Hello, Today we are going to be looking at validating credit card, adding a credit card to our app needs some level of validation before it will be store in the database.

Click on my [profile](https://dev.to/kingsconsult) to follow me to get more updates.

### **Step 1: Install the package required**
We are going to be using a package **Laravel Validator Rules - Credit Card**, so we need to install it
> composer require laravel-validation-rules/credit-card

![install LVR](https://res.cloudinary.com/kingsconsult/image/upload/v1610186481/laravel%20form%20validation/1_s3zekv.png)

### **Step 2: Create the Form Request**
For a comprehensive explanation of this step, check out this material [Laravel Form Validation](https://dev.to/kingsconsult/laravel-form-validation-5dla/edit)
> php artisan make:request CardVerificationRequest

### **Step 3: Write the Form Request Rules and Error Message**
Open the file that is created in **app/Http/Requests/**, **CardVerificationRequest.php** and edit to this
```
<?php

namespace App\Http\Requests;

use LVR\CreditCard\CardCvc;
use LVR\CreditCard\CardNumber;
use LVR\CreditCard\CardExpirationYear;
use LVR\CreditCard\CardExpirationMonth;
use Illuminate\Foundation\Http\FormRequest;

class CardVerificationRequest 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 [
            'card_number' => ['required', 'unique:cards,cardNo', new CardNumber],
            'expiration_year' => ['required', new CardExpirationYear($this->get('expiration_month'))],
            'expiration_month' => ['required', new CardExpirationMonth($this->get('expiration_year'))],
            'cvc' => ['required', new CardCvc($this->get('card_number'))]
        ];
    }

    public function messages()
    {
        return [
            'card_number.required' => 'The card number is compulsory'
        ];
    }
}
```
### **Step 4: Type-hint the CardVerificationRequest in our Controller**
Go to the controller method, where you want to use the validation and use my code as a guide
```
    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\CardVerificationRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CardVerificationRequest $request)
    {

        $validatedData = $request->validated();

        $newCard = new Card;
        
        $newCard->cardNo = $validatedData["card_number"];
        $newCard->cardExpiringMonth = $validatedData["expiration_month"];
        $newCard->cardExpiringYear = $validatedData["expiration_year"];
        $newCard->cardCVV = $validatedData["cvc"];

        $newCard->save();

        return response()->json([
            "status" => "success",
            "message" => "Card saved successfully.",
            "data" => $newCard
        ], StatusCodes::SUCCESS);
    }
```

### **Testing**
Running the app with fields that violates the rules
![error](https://res.cloudinary.com/kingsconsult/image/upload/v1610186482/laravel%20form%20validation/2_vn5eqr.png)
When the fields are correct
![successful](https://res.cloudinary.com/kingsconsult/image/upload/v1610186481/laravel%20form%20validation/3_db0dmk.png)


Follow me for more of my articles, you can leave comments, suggestions, and reactions.
I am open to any vacancy as a PHP (Laravel) backend engineer, I am also available for any job. 

[click the link to view my profile and follow me] (https://dev.to/kingsconsult)

Thank you for your time