[Validator] NotBlank: add a new option to allow null values
This commit is contained in:
parent
98bc3e7917
commit
484d22a6d9
@ -6,6 +6,7 @@ CHANGELOG
|
||||
|
||||
* added options `iban` and `ibanPropertyPath` to Bic constraint
|
||||
* added UATP cards support to `CardSchemeValidator`
|
||||
* added option `allowNull` to NotBlank constraint
|
||||
|
||||
4.2.0
|
||||
-----
|
||||
|
@ -18,6 +18,7 @@ use Symfony\Component\Validator\Constraint;
|
||||
* @Target({"PROPERTY", "METHOD", "ANNOTATION"})
|
||||
*
|
||||
* @author Bernhard Schussek <bschussek@gmail.com>
|
||||
* @author Kévin Dunglas <dunglas@gmail.com>
|
||||
*/
|
||||
class NotBlank extends Constraint
|
||||
{
|
||||
@ -28,4 +29,5 @@ class NotBlank extends Constraint
|
||||
];
|
||||
|
||||
public $message = 'This value should not be blank.';
|
||||
public $allowNull = false;
|
||||
}
|
||||
|
@ -17,6 +17,7 @@ use Symfony\Component\Validator\Exception\UnexpectedTypeException;
|
||||
|
||||
/**
|
||||
* @author Bernhard Schussek <bschussek@gmail.com>
|
||||
* @author Kévin Dunglas <dunglas@gmail.com>
|
||||
*/
|
||||
class NotBlankValidator extends ConstraintValidator
|
||||
{
|
||||
@ -29,6 +30,10 @@ class NotBlankValidator extends ConstraintValidator
|
||||
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\NotBlank');
|
||||
}
|
||||
|
||||
if ($constraint->allowNull && null === $value) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (false === $value || (empty($value) && '0' != $value)) {
|
||||
$this->context->buildViolation($constraint->message)
|
||||
->setParameter('{{ value }}', $this->formatValue($value))
|
||||
|
@ -98,4 +98,30 @@ class NotBlankValidatorTest extends ConstraintValidatorTestCase
|
||||
->setCode(NotBlank::IS_BLANK_ERROR)
|
||||
->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();
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user