Search code examples
laravellaravel-5.4request-validation

Customized validation rule on laravel form request validation


I do have a registration form in my laravel 5.4 application and laravel form request validation is used for server side validation. Some fields in this form are populated dynamically using calculations in javascript which need to be validated against user inputs.

The user input fields in the form are 'quantity', 'rate' and 'discount'.

The populated fields are 'total' and 'bill_amount'.

What i need to validate are :

  1. Check 'total' equal to 'quantity' * 'rate'.
  2. Check 'bill_amount' equal to 'total' - 'rate'

I would prefer laravel form request validation methods for this validation. I have tried to use methods like After Hooks and conditionally adding rule etc. and failed.

In simple words the requirement is : check if a field is equal to product of other two fields, and invalidate if not equal and validate if equal.(using form request validation.)

Thanks in advance!


Solution

  • After a long time I was able to find this solution.

    Form request After Hooks can be used to achieve the result: [I was unable to find this logic before]

    public function withValidator($validator)
        {
            $quanty     = $this->request->get("quantity");
            $rate       = $this->request->get("rate");
            $billAmount = $this->request->get("bill_amount");
    
            $validator->after(function ($validator) {
                if(($quanty * $rate) != $billAmount) {
                    $validator->errors()->add('bill_amount', 'Something went wrong with this field!');
                }
            });
        }