0
0
LaravelHow-ToBeginner · 3 min read

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 min and max to the wrong data type (e.g., using string rules on numbers).
  • For strings, forgetting that min and max check length, not numeric value.
  • Not combining required rule, 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

RuleDescriptionApplies To
min:valueMinimum length or value allowedstrings, numbers, arrays, files
max:valueMaximum length or value allowedstrings, numbers, arrays, files
requiredField must be present and not emptyall types
integerField must be an integernumbers

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.