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,valuecorresponds to the number of characters. For numeric data,valuecorresponds to the integer value. For arrays,sizecorresponds to thecountof the array. For files,sizecorresponds 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:
-
Trace validation logic in
\Illuminate\Validation\Validator::fails()
Laravel
Core validation method:$this->validateAttribute($attribute, $rule); -
Dynamic method generation for validation rules
Laravel
(The resolved method here isvalidateSize) -
Locate the method in
ValidatesAttributes::validateSize
Laravel -
Key logic checks
$hasNumericcondition
Laravel
$hasNumericis determined by:
Laravel -
Validation flow without
numeric/integerrules
Laravel
Laravel
Missing numeric check returnsnull, making$hasNumericfalse:
Laravel
Conclusion: Always combine size with numeric or integer when validating numbers:
'age' => 'required|integer|size:9'
// or
'age' => 'required|numeric|size:9'