phpvalidationlaravel-5

Laravel 5.6 FormRequest validation


I have set of input fields to be validated. I have removed commas (since user enters comma as thousand separator) before validation takes place. But it still complains that the number is not numeric.

class UpdateFamilyExpense extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function sanitize()
    {
        $attributes = $this->all();

        for ($i=1; $i<=15; $i++)
        {
            $attributes['e'.$i] = str_replace(',', '', $attributes['e'.$i]);
        }
        $this->replace($attributes);
    }

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

        return [
            'e1' =>    'required|numeric',
        ];
    }

    public function messages()
    {
        return [
            'e1.required' => 'required',
            'e1.numeric' =>  'must be a numeric',
        ];
    }
}

I cannot figure out where I am wrong. Can someone help me figure out what I am missing here?


Solution

  • Override prepareForValidation as:

    protected function prepareForValidation()
    {
        $this->sanitize();
    }