Current Location: Home> Latest Articles> Comprehensive Guide to Laravel Form Numeric Size Validation with Examples

Comprehensive Guide to Laravel Form Numeric Size Validation with Examples

M66 2025-08-06

Introduction to Laravel Form Validation

Form validation is a crucial step in Laravel web application development to ensure user input meets expected criteria. Validating forms helps maintain application stability and security.

Laravel offers powerful validation features supporting rules such as required fields, length constraints, data types, and uniqueness. Developers can define validation rules and call the validate() method to easily validate data and handle errors.

Understanding the Size Validation Rule for Numeric Inputs

When handling numeric form inputs, it is often necessary to restrict the size or length of the number to guarantee valid data. Laravel’s size validation rule serves this purpose.

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

Example of Using Size Validation for Numbers in Laravel

Here is a simple example demonstrating how to use the size validation rule for numbers in Laravel.

Suppose you require users to input their age, which must be exactly two digits long (i.e., between 10 and 99). You can define the validation rule as follows:

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

In this rule, required means the field is mandatory, integer ensures the input is an integer, and size:2 enforces that the number has exactly two digits.

During form submission, just call the validate() method to perform the validation:

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

If the user inputs a number outside the two-digit range, validation will fail and an error message will be returned.

Important Considerations When Using the Size Rule

Please keep these points in mind when using the size validation rule:

  • The size rule applies to both strings and numeric types, checking string length or the number of digits for numbers.
  • For numeric values, size validates the number of digits, not the numeric value itself. For example, size:2 matches any integer between 10 and 99.
  • Ensure the rule aligns with the data type of the field to avoid validation issues.

Conclusion

Using Laravel’s size validation rule effectively limits the digit length of numeric form inputs, enhancing the security and accuracy of your application. Defining rules and calling validate() is straightforward, making it suitable for various validation scenarios. This guide and examples should assist you in mastering numeric validation in Laravel forms.