From 45291e711f7109c225d676b9c423d5d9fc517ea9 Mon Sep 17 00:00:00 2001 From: lionelkimbs Date: Mon, 4 Mar 2024 01:17:31 +0100 Subject: [PATCH] [Validator] Fix NotBlank validator to treat whitespace-only strings as blank --- Constraints/NotBlankValidator.php | 3 +++ Tests/Constraints/NotBlankValidatorTest.php | 14 ++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/Constraints/NotBlankValidator.php b/Constraints/NotBlankValidator.php index acc81040c..3b749a9d6 100644 --- a/Constraints/NotBlankValidator.php +++ b/Constraints/NotBlankValidator.php @@ -18,6 +18,7 @@ /** * @author Bernhard Schussek * @author Kévin Dunglas + * @author Lionel Kimb's */ class NotBlankValidator extends ConstraintValidator { @@ -35,6 +36,8 @@ public function validate(mixed $value, Constraint $constraint): void $value = ($constraint->normalizer)($value); } + $value = is_string($value) ? trim($value) : $value; + if (false === $value || (empty($value) && '0' != $value)) { $this->context->buildViolation($constraint->message) ->setParameter('{{ value }}', $this->formatValue($value)) diff --git a/Tests/Constraints/NotBlankValidatorTest.php b/Tests/Constraints/NotBlankValidatorTest.php index 8d1ba3d0f..b55eb199b 100644 --- a/Tests/Constraints/NotBlankValidatorTest.php +++ b/Tests/Constraints/NotBlankValidatorTest.php @@ -71,6 +71,20 @@ public function testBlankIsInvalid() ->assertRaised(); } + public function testBlankTextIsInvalid() + { + $constraint = new NotBlank([ + 'message' => 'myMessage', + ]); + + $this->validator->validate(' ', $constraint); + + $this->buildViolation('myMessage') + ->setParameter('{{ value }}', '""') + ->setCode(NotBlank::IS_BLANK_ERROR) + ->assertRaised(); + } + public function testFalseIsInvalid() { $constraint = new NotBlank([