IntVal: Validate negative numbers properly

This commit is contained in:
Alexander Wühr 2021-05-05 13:24:38 +02:00
parent 3dcd859d98
commit 660294128f
No known key found for this signature in database
GPG key ID: 0B7107C9393169F4
3 changed files with 24 additions and 2 deletions

View file

@ -13,8 +13,9 @@ declare(strict_types=1);
namespace Respect\Validation\Rules;
use function ctype_digit;
use function is_int;
use function is_string;
use function preg_match;
/**
* Validates if the input is an integer.
@ -36,6 +37,10 @@ final class IntVal extends AbstractRule
return true;
}
return ctype_digit($input);
if (!is_string($input)) {
return false;
}
return preg_match('/^-?\d+$/', $input) === 1;
}
}

View file

@ -35,9 +35,23 @@ try {
} catch (NestedValidationException $exception) {
echo $exception->getFullMessage() . PHP_EOL;
}
try {
v::not(v::intVal())->assert(-42);
} catch (NestedValidationException $exception) {
echo $exception->getFullMessage() . PHP_EOL;
}
try {
v::not(v::intVal())->assert('-42');
} catch (NestedValidationException $exception) {
echo $exception->getFullMessage() . PHP_EOL;
}
?>
--EXPECT--
"42.33" must be an integer number
2 must not be an integer number
- "Foo" must be an integer number
- 3 must not be an integer number
- -42 must not be an integer number
- "-42" must not be an integer number

View file

@ -49,6 +49,9 @@ final class IntValTest extends RuleTestCase
[$rule, 0b101010],
[$rule, 0x2a],
[$rule, '089'],
[$rule, -42],
[$rule, '-42'],
[$rule, '-042'],
];
}