Featured image of post Laravel Form size Validation for Numbers

Laravel Form size Validation for Numbers

Elegant Data Validation

To validate a numeric exact value, I referred to the form validation documentation:

size:value
The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to the integer value. For arrays, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes.

Original validation rule:

$data = ['age' => 9];  

$validator = \Illuminate\Support\Facades\Validator::make($data, ['age' => 'required|size:9']);  
if ($validator->fails()) {  
    dd($validator->errors()->first());  
}  
dd('pass');  

I expected it to validate numbers directly when the input 9 is an integer. However, it returned an error message:
The age must be 9 characters.

This message clearly indicates string length validation. Upon further investigation, I realized we need to add the numeric or integer rule.


Code analysis:

  1. Trace validation logic in \Illuminate\Validation\Validator::fails()


    Core validation method: $this->validateAttribute($attribute, $rule);

  2. Pre-validation filtering for file uploads

  3. Dynamic method generation for validation rules


    (The resolved method here is validateSize)

  4. Locate the method in ValidatesAttributes::validateSize

  5. Key logic checks $hasNumeric condition


    $hasNumeric is determined by:

  6. Validation flow without numeric/integer rules



    Missing numeric check returns null, making $hasNumeric false:

Conclusion: Always combine size with numeric or integer when validating numbers:

'age' => 'required|integer|size:9'  
// or  
'age' => 'required|numeric|size:9'