diff --git a/validation/custom_constraint.rst b/validation/custom_constraint.rst index 2430143dd0e..f67b3630276 100644 --- a/validation/custom_constraint.rst +++ b/validation/custom_constraint.rst @@ -59,11 +59,22 @@ The validator class is also simple, and only has one required method ``validate( use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; + use Symfony\Component\Validator\Exception\UnexpectedTypeException; class ContainsAlphanumericValidator extends ConstraintValidator { public function validate($value, Constraint $constraint) { + // custom constraints should ignore null and empty values to allow + // other constraints (NotBlank, NotNull, etc.) take care of that + if (null === $value || '' === $value) { + return; + } + + if (!is_string($value)) { + throw new UnexpectedTypeException($value, 'string'); + } + if (!preg_match('/^[a-zA-Z0-9]+$/', $value, $matches)) { // If you're using the new 2.5 validation API (you probably are!) $this->context->buildViolation($constraint->message)