How to Use Min Max Rule in Laravel Validation
In Laravel, use the
min and max validation rules to set minimum and maximum limits on input values or string lengths. These rules are added in the validation array, like 'age' => 'min:18|max:65' for numbers or 'name' => 'min:3|max:50' for strings.Syntax
The min and max rules are used inside Laravel's validation array to restrict input values or string lengths.
- min:value: Sets the minimum allowed value or length.
- max:value: Sets the maximum allowed value or length.
- Works for strings, numbers, arrays, and files (size in kilobytes).
php
'field_name' => 'min:value|max:value'
Example
This example shows how to validate a user's name and age using min and max rules in a Laravel controller.
php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UserController extends Controller { public function store(Request $request) { $validated = $request->validate([ 'name' => 'required|string|min:3|max:50', 'age' => 'required|integer|min:18|max:65', ]); // If validation passes, proceed return response()->json(['message' => 'User data is valid', 'data' => $validated]); } }
Output
{"message":"User data is valid","data":{"name":"John Doe","age":30}}
Common Pitfalls
Common mistakes when using min and max rules include:
- Applying
minandmaxto the wrong data type (e.g., using string rules on numbers). - For strings, forgetting that
minandmaxcheck length, not numeric value. - Not combining
requiredrule, which can cause unexpected passes.
php
<?php // Wrong: min and max used on string but expecting numeric value $request->validate([ 'age' => 'required|string|min:18|max:65', // Incorrect ]); // Right: Use integer for numeric validation $request->validate([ 'age' => 'required|integer|min:18|max:65', ]);
Quick Reference
| Rule | Description | Applies To |
|---|---|---|
| min:value | Minimum length or value allowed | strings, numbers, arrays, files |
| max:value | Maximum length or value allowed | strings, numbers, arrays, files |
| required | Field must be present and not empty | all types |
| integer | Field must be an integer | numbers |
Key Takeaways
Use
min and max in Laravel validation to limit input length or value.Combine
min and max with the correct data type rules like string or integer.Remember
min and max check length for strings and numeric value for numbers.Always include
required if the field must not be empty.Test validation with different inputs to avoid common mistakes.