[Validator] NotBlank: add a new option to allow null values

This commit is contained in:
Kévin Dunglas 2018-12-18 11:24:49 +01:00 committed by Fabien Potencier
parent 98bc3e7917
commit 484d22a6d9
4 changed files with 34 additions and 0 deletions

View File

@ -6,6 +6,7 @@ CHANGELOG
* added options `iban` and `ibanPropertyPath` to Bic constraint * added options `iban` and `ibanPropertyPath` to Bic constraint
* added UATP cards support to `CardSchemeValidator` * added UATP cards support to `CardSchemeValidator`
* added option `allowNull` to NotBlank constraint
4.2.0 4.2.0
----- -----

View File

@ -18,6 +18,7 @@ use Symfony\Component\Validator\Constraint;
* @Target({"PROPERTY", "METHOD", "ANNOTATION"}) * @Target({"PROPERTY", "METHOD", "ANNOTATION"})
* *
* @author Bernhard Schussek <bschussek@gmail.com> * @author Bernhard Schussek <bschussek@gmail.com>
* @author Kévin Dunglas <dunglas@gmail.com>
*/ */
class NotBlank extends Constraint class NotBlank extends Constraint
{ {
@ -28,4 +29,5 @@ class NotBlank extends Constraint
]; ];
public $message = 'This value should not be blank.'; public $message = 'This value should not be blank.';
public $allowNull = false;
} }

View File

@ -17,6 +17,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/** /**
* @author Bernhard Schussek <bschussek@gmail.com> * @author Bernhard Schussek <bschussek@gmail.com>
* @author Kévin Dunglas <dunglas@gmail.com>
*/ */
class NotBlankValidator extends ConstraintValidator class NotBlankValidator extends ConstraintValidator
{ {
@ -29,6 +30,10 @@ class NotBlankValidator extends ConstraintValidator
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\NotBlank'); throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\NotBlank');
} }
if ($constraint->allowNull && null === $value) {
return;
}
if (false === $value || (empty($value) && '0' != $value)) { if (false === $value || (empty($value) && '0' != $value)) {
$this->context->buildViolation($constraint->message) $this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value)) ->setParameter('{{ value }}', $this->formatValue($value))

View File

@ -98,4 +98,30 @@ class NotBlankValidatorTest extends ConstraintValidatorTestCase
->setCode(NotBlank::IS_BLANK_ERROR) ->setCode(NotBlank::IS_BLANK_ERROR)
->assertRaised(); ->assertRaised();
} }
public function testAllowNullTrue()
{
$constraint = new NotBlank([
'message' => 'myMessage',
'allowNull' => true,
]);
$this->validator->validate(null, $constraint);
$this->assertNoViolation();
}
public function testAllowNullFalse()
{
$constraint = new NotBlank([
'message' => 'myMessage',
'allowNull' => false,
]);
$this->validator->validate(null, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', 'null')
->setCode(NotBlank::IS_BLANK_ERROR)
->assertRaised();
}
} }