0

I am creating app in laravel 5.8

I am using http://autonumeric.org/ for my price field in order to separate every three digits with comma. So for a number with more than 3 digits it will have a comma.

Input validation for integer fails if I enter more than 3 digits!. Obviously it is because of the comma. Therefore I tried sanitizing the input before validation. but the problem remains!

I tried to cast the sanitized versions of inputs to int but it still does not work!

This is how my request class look like:

public function rules()
    {
        $this->sanitize();

        return [
                   'base_price' => 'required|integer', //it fails if I enter a number with more than 3 digits!
                 ];


    }

    public function sanitize()
    {
        $input = $this->all();
        //sanitize
        $input['base_price'] = filter_var($input['base_price'], FILTER_SANITIZE_NUMBER_INT);
        //casting
        $input['base_price'] = (int) $input[base_price'];
        $this->replace($input);
    }
Hadi Aghandeh
  • 765
  • 6
  • 24

1 Answers1

0

For those who might face the same problem, I am going to answer my own question.

Thankfully for the help of @Sohel0415 in the comments I was able to fix the problem.

as mentioned in this question: Modify input before validation on Laravel 5.1. Calling sanitize() in the rule() will not change the inputs before validation. It sanitizes and modifies the inputs but this modification is only used after validation. This is because the inputs are already loaded for validation.

The FormRequest class actually uses the validationData() method to access the data which are going to be validated and this happens before calling for the rule().

 protected function validationData() //the method inside Illuminate\Foundation\Http\FormRequest;
{
    return $this->all();
}

Therefore if we only override this method in our request class we can fix the problem.:

 protected function validationData()
{
    $this->sanitize();
    return parent::validationData(); // TODO: Change the autogenerated stub
}
Hadi Aghandeh
  • 765
  • 6
  • 24