How to do non negative integers validation in Laravel?

Laravel provides many ways of validating user input. Integer validation is to assure that the entered data has digits and numbers. Positive or non negative integers validation is necessary when dealing with data like age, price values, quantities, etc. The values in which negative entries are not permitted.

We can define Laravel validation rules in the Controller class. The rules are applied before saving or storing user data in the application and database. Validation rules can be applied to many types of inputs from a user.

There are separate rules defined for mobile numbers, maximum character validations, and image and video uploads. For example, checking image dimensions. Let’s check the rule to check for only positive integer entry.

Validation rule for non negative integers

Validation rule for only positive entries can be used as shown below.

 public function save()
         'price' => 'required|numeric|gt:0',

The above rule within the validate function checks the price entries. If the price entered meets the mentioned criteria, then it can be saved in the database, otherwise relevant validation error pops up.

  • The ‘required’ assures price entries are not empty.
  • ‘Numeric’ checks if only digits, either float or integers are entered.
  • The ‘gt:0’ checks if numbers greater than 0 are entered.

The set of rules assures that only non-negative integers are entered for the price variable. This form of validation is very useful when we work on applications where only positive entries are permitted.