Skip to content

Commit 676fc4e

Browse files
committed
minor #9993 Made the code of a validation example more robust (javiereguiluz)
This PR was squashed before being merged into the 2.8 branch (closes #9993). Discussion ---------- Made the code of a validation example more robust Fixes #9979. Commits ------- 53e2af1 Made the code of a validation example more robust
2 parents 1c855de + 53e2af1 commit 676fc4e

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

validation/custom_constraint.rst

+11
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,22 @@ The validator class is also simple, and only has one required method ``validate(
5959

6060
use Symfony\Component\Validator\Constraint;
6161
use Symfony\Component\Validator\ConstraintValidator;
62+
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
6263

6364
class ContainsAlphanumericValidator extends ConstraintValidator
6465
{
6566
public function validate($value, Constraint $constraint)
6667
{
68+
// custom constraints should ignore null and empty values to allow
69+
// other constraints (NotBlank, NotNull, etc.) take care of that
70+
if (null === $value || '' === $value) {
71+
return;
72+
}
73+
74+
if (!is_string($value)) {
75+
throw new UnexpectedTypeException($value, 'string');
76+
}
77+
6778
if (!preg_match('/^[a-zA-Z0-9]+$/', $value, $matches)) {
6879
// If you're using the new 2.5 validation API (you probably are!)
6980
$this->context->buildViolation($constraint->message)

0 commit comments

Comments
 (0)