简体   繁体   English

Symfony 4 自定义验证器约束未加载

[英]Symfony 4 Custom Validator Constraint is not loading

I'm trying to create a custom Validator in my Symfony 4.4 project described in https://symfony.com/doc/current/validation/custom_constraint.html我正在尝试在https://symfony.com/doc/current/validation/custom_constraint.html 中描述的我的 Symfony 4.4 项目中创建自定义验证器

I have added the next files:我添加了下一个文件:

src/Validator/Constraints/PhoneNumber.php 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 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();
        }
    }
}

config/validator/validation.yaml配置/验证器/validation.yaml

App\Entity\AcmeEntity:
    properties:
        name:
            - NotBlank: ~
            - App\Validator\Constraints\ContainsAlphanumeric: ~

After i have tried the above the validator doesn't respond... So next thing i have tried is to add the validator constraint to my Entity Contact.在我尝试了上述操作之后,验证器没有响应......所以我接下来尝试的是将验证器约束添加到我的实体联系人中。

src/Entity/Contact.php源代码/实体/Contact.php

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;

use App\Validator\Constraints as CustomAssert ;

/**
 * @ApiResource()
 * @ORM\Entity(repositoryClass="App\Repository\ContactRepository")
 */
class Contact
{

    .....


    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @CustomAssert\PhoneNumber
     */
    private $phoneNumber;

This is also not working.这也行不通。

Someone who see what i am doing wrong or have a suggestion for what i can try?有人看到我做错了什么或对我可以尝试的事情有建议吗? Thanks in advance!提前致谢!

Is it possible that the contraint you are looking for is set from a related entity?您正在寻找的约束是否可能是从相关实体设置的? if so, then try to pass the validation from the first to the second entity.如果是,则尝试将验证从第一个实体传递到第二个实体。

This can be done by:这可以通过以下方式完成:

@Assert\Valid()

dont forget to use it:不要忘记使用它:

use Symfony\Component\Validator\Constraints as Assert; 

 class Contact { ..... /** * @ORM\\Column(type="string", length=255, nullable=true) * @CustomAssert\\PhoneNumber */ private $phoneNumber; class Person { ..... /** * @ORM\\OneToOne(targetEntity="App\\Entity\\Contact") * @Assert\\Valid() */ private $contact;

you can try to implement the validateBy method in your PhoneNumber class.您可以尝试在PhoneNumber类中实现validateBy方法。 In normal cases you don't need to do that because the default behavior is to look for the same Constraint name suffixed by Validator (which will be PhoneNumberValidator ).在正常情况下,您不需要这样做,因为默认行为是查找以Validator为后缀的相同 Constraint 名称(即PhoneNumberValidator )。

An other reason for that is could be the call to validate method of the ValidatorInterface .另一个原因可能是调用ValidatorInterface validate方法。 Maybe you're passing some validations groups (if you can share that part with us here) and in that case you i'll need to specify that in the annotation @CustomAssert\\PhoneNumber(groups={"some_group"}) .也许您正在传递一些验证组(如果您可以在此处与我们共享该部分),在这种情况下,您需要在注释@CustomAssert\\PhoneNumber(groups={"some_group"})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM