Current Location: Home> Latest Articles> Detailed Guide and Examples of Laravel Form Number Size Validation

Detailed Guide and Examples of Laravel Form Number Size Validation

M66 2025-08-06

Introduction to Laravel Form Validation

When developing web applications with the Laravel framework, form validation is a crucial step to ensure submitted data meets expected criteria. It helps improve the stability and security of the application.

Laravel comes with a powerful set of validation rules that allow checking for required fields, length, data types, uniqueness, and more. Developers simply define the rules and call the validate() method to perform automatic validation and handle errors effectively.

Overview of Number Size Validation in Forms

For forms that require numeric input, it's often necessary to limit the size or length of the numbers to ensure data integrity. Laravel's size validation rule is designed to address this need.

The size rule validates whether a given value has the exact length or size, applicable to both strings and numbers. For example, size:5 checks if the value is exactly 5 characters or digits long.

Example of Using Size Validation for Numbers in Laravel

Below is a simple example showing how to apply the size validation rule to a number field in Laravel.

Suppose you require the user to enter their age, which must be a two-digit integer between 10 and 99. The validation rules can be set as follows:

$rules = [
    'age' => 'required|integer|size:2'
];

Here, required means the field is mandatory, integer restricts input to integers, and size:2 specifies the number must be exactly two digits.

When processing the form submission, simply call the validate() method to perform validation:

public function store(Request $request)
{
    $rules = [
        'age' => 'required|integer|size:2'
    ];
    $this->validate($request, $rules);
    // Handle the validated data...
}

Inputs like 12 or 97 will pass validation, while others outside the two-digit range will trigger error messages.

Important Notes on Using the Size Rule

When applying the size validation rule, keep in mind the following:

  • The size rule applies to both strings and numeric fields.
  • The specified size must align with the type of the field.
  • For integers, the size rule checks the number of digits, not the numeric value range. For instance, size:2 matches any two-digit integer between 10 and 99.

Conclusion

Laravel's size validation rule offers an effective way to enforce length or size constraints on form inputs, helping prevent invalid data and enhancing application security. By defining rules clearly and calling the validate method, developers can easily enforce numeric digit constraints. Understanding the rule's scope and nuances ensures validation aligns well with business requirements.

We hope this article helps you implement number validation in your Laravel projects successfully.