我正在尝试在https://symfony.com/doc/current/validation/custom_constraint.html中描述的 Symfony 4.4 项目中创建自定义验证器
我添加了下一个文件:
src/Validator/Constraints/PhoneNumber.php
<?php
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class PhoneNumber extends Constraint
{
public $message = 'The string contains an illegal character: it can only contain letters or numbers.';
}
src/Validator/Constraints/PhoneNumberValidator.php
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
class PhoneNumberValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
dd('er wordt gevalideerd!');
if (!$constraint instanceof PhoneNumber) {
throw new UnexpectedTypeException($constraint, PhoneNumber::class);
}
// 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 this exception if your validator cannot handle the passed type so that it can be marked as invalid
throw new UnexpectedValueException($value, 'string');
// separate multiple types using pipes
// throw new UnexpectedValueException($value, 'string|int');
}
if (!preg_match('/^[a-zA-Z0-9]+$/', $value, $matches)) {
// the argument must be a string or an object implementing __toString()
$this->context->buildViolation($constraint->message)
->setParameter('{{ string }}', $value)
->addViolation();
}
}
}
在我尝试了上述方法之后,验证器没有响应......所以接下来我尝试将验证器约束添加到我的实体联系人中。
这也行不通。
有人看到我做错了什么或对我可以尝试什么有建议?提前致谢!
BIG阳
幕布斯6054654