If id parameter except of integer value has a space symbol inside, this code will pass the validation without any problems:
$v = Validator::make($request->all(), [
'id' => 'required|integer',
]);
if ($v->fails()) {
return $this->respondBadRequest($v->errors());
}
while $request->input('id') still is a string with a space. I think, many developers use integer validation rule and are sure that the value is 100% integer after validation.
[ ]123 will pass
123[ ] will pass
[ ]123[ ] will pass
1[ ]23 will fail
PHP considers an integer with a leading or trailing space as integer, that's why the validation passes.
Strings like 42 cats can be cast to 42 as an integer in PHP. No idea why they thought that would be a good idea.
Yeah that is strange, it makes you think twice before casting a string to integer.
PHP considers an integer with a leading or trailing space as integer
$a = '1 ';
var_dump($a); // string(2) "1 "
is_int($a) is false too.
May be you mean that GET parameters always are strings? That's true.
@GrahamCampbell so in this case validation doesn't really validate, but tries to convert a given string into integer, and if it's succeed, returns a positive result. But the string is not converted into integer after validation. And I'm sure many developers who use 'integer' validation rule are sure that after validation this string has an integer type, but it's still a string with any symbols including dangerous. They have to manually use intval() for all such parameters.
@Chimit The Validator doesn't modify the given attributes, it only validates. While many developers might expect [ ]1 to return false, some others would expect it to be true since filtering with FILTER_VALIDATE_INT will consider it true. So PHP considers it as a valid integer.
@DeeJaVu Can I ask why you are downvoting every single comment I make on any issue? I'm considering reporting you to GitHub.
Think of a form input where you type for age [26 ], the trailing space here will be ignored and the value will be validated as an integer successfully.
I'd be happy to see another stronger integer validator though. I'd like to see a PR to add a new validation rule that's more strict.
@themsaid sure, but it would be saved in the DB as integer 26 or string [26], not as string [26 ].
I'm not sure, but I think it's a very unclear place, and somebody could rely on validation and put such string into the DB without other sanitization.
At least the Laravel documentation should point on this moment. Or renaming "integer" to "integerable" is needed :)
Most helpful comment
I'd be happy to see another stronger integer validator though. I'd like to see a PR to add a new validation rule that's more strict.