How to validation form data encrypted value on Laravel request file

100 views Asked by At

Here is my code "FormRequest" class

public function rules()
{
    return [
        'person_id' => 'required|numeric',
        'name' => 'required|max:32',
    ];
}

public function messages()
{
    return [
        'person_id.required' => 'Person is required',
        'person_id.numeric' => 'Person must be numeric',
        'name.required' => 'Name is required',
        'name.max' => 'Name maximum character limit is 32',
    ];
}

Here "person_id" is encrypted like "base64_encode, or encrypt()" When the form is submitted, the error shows is this data is not numeric. So I want to "base64_decode, or decrypt()" for validation, but I don't know how.

1

There are 1 answers

0
Karl Hill On

In Laravel, you can use the decrypt function to decrypt an encrypted value. However, you can't directly apply this function in the validation rules. Instead, you can use the prepareForValidation method in your form request class to decrypt the person_id before validation.

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Crypt;

class YourFormRequest extends FormRequest
{
    protected function prepareForValidation()
    {
        $this->merge([
            'person_id' => Crypt::decryptString($this->person_id),
        ]);
    }

    public function rules()
    {
        return [
            'person_id' => 'required|numeric',
            'name' => 'required|max:32',
        ];
    }

    public function messages()
    {
        return [
            'person_id.required' => 'Person is required',
            'person_id.numeric' => 'Person must be numeric',
            'name.required' => 'Name is required',
            'name.max' => 'Name maximum character limit is 32',
        ];
    }
}