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 thecount
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:
-
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
$hasNumeric
condition
Laravel
$hasNumeric
is determined by:
Laravel -
Validation flow without
numeric
/integer
rules
Laravel
Laravel
Missing numeric check returnsnull
, making$hasNumeric
false:
Laravel
Conclusion: Always combine size
with numeric
or integer
when validating numbers:
'age' => 'required|integer|size:9'
// or
'age' => 'required|numeric|size:9'