Laravel: Validate min and max value based on input fields

14,607

Solution 1

You can use the code below

$validator=validator($request->all(),[
    'min_price'=>'required|min:1',
    'max_price' => 'required|gt:min_price'
]);

References

Solution 2

You can use the rule gt (Greather than) that expect the number of another field as first argument:

'min_price'=>'required|numeric|min:30',
'max_price'=>'required|numeric|gt:min_price'
Share:
14,607

Related videos on Youtube

Arpit Aggarwal
Author by

Arpit Aggarwal

I have little knowledge of C,C++, java(core), android(basic), HTML, CSS, javascript, jquery, php, ajax, yii2 and wordpress

Updated on June 04, 2022

Comments

  • Arpit Aggarwal
    Arpit Aggarwal almost 2 years

    I am trying to add validation for the min and max values. Both these values are coming from input fields.

    I want to validate that max value (max_price) should always be greater than min value (min_price).

    I am working on the Laravel 5.7

    $validator = validator($request->all(),[
      'min_price' => 'required|min:1"',
      'max_price' => 'required|numeric|min:min_price',
    ]);
    
  • Nico Haase
    Nico Haase about 5 years
    Can you explain what you've changed and why? Keep in mind that others should be able to learn from your answer
  • lovepreet singh
    lovepreet singh about 5 years
    because gte match value greater than or equal and you say that you get value greater than that i have changed from gte to gt now you can get get value greater than
  • Nico Haase
    Nico Haase about 5 years
    Please add all such explanation to the answer itself.
  • Arpit Aggarwal
    Arpit Aggarwal about 5 years
    Thnx for the solution and refrence. It worked fyn. There is just 1 issue. If we keep min_price field empty then it crashes.