Skip to content
Permalink
Browse files

feature #29641 [Validator] NotBlank: add a new option to allow null v…

…alues (dunglas)

This PR was squashed before being merged into the 4.3-dev branch (closes #29641).

Discussion
----------

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

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes <!-- don't forget to update src/**/CHANGELOG.md files -->
| BC breaks?    | no     <!-- see https://symfony.com/bc -->
| Deprecations? | no <!-- don't forget to update UPGRADE-*.md and src/**/CHANGELOG.md files -->
| Tests pass?   | yes    <!-- please add some, will be required by reviewers -->
| Fixed tickets | #27876
| License       | MIT
| Doc PR        | todo

This PR adds a new option to the `@notblank` constraint to allow null values. As described in #27876, this is particularly useful when creating web APIs.

Commits
-------

484d22a [Validator] NotBlank: add a new option to allow null values
  • Loading branch information...
fabpot committed Jan 29, 2019
2 parents dca0975 + 484d22a commit be5d85e112471c3876a3abf2250bf47abcb37359
@@ -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 @@
* @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 @@
/**
* @author Bernhard Schussek <bschussek@gmail.com>
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class NotBlankValidator extends ConstraintValidator
{
@@ -29,6 +30,10 @@ public function validate($value, Constraint $constraint)
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 @@ public function testEmptyArrayIsInvalid()
->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();
}
}

0 comments on commit be5d85e

Please sign in to comment.
You can’t perform that action at this time.