簡體   English   中英

Symfony 4 自定義驗證器約束未加載

[英]Symfony 4 Custom Validator Constraint is not loading

我正在嘗試在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();
        }
    }
}

配置/驗證器/validation.yaml

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

在我嘗試了上述操作之后,驗證器沒有響應......所以我接下來嘗試的是將驗證器約束添加到我的實體聯系人中。

源代碼/實體/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;

這也行不通。

有人看到我做錯了什么或對我可以嘗試的事情有建議嗎? 提前致謝!

您正在尋找的約束是否可能是從相關實體設置的? 如果是,則嘗試將驗證從第一個實體傳遞到第二個實體。

這可以通過以下方式完成:

@Assert\Valid()

不要忘記使用它:

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;

您可以嘗試在PhoneNumber類中實現validateBy方法。 在正常情況下,您不需要這樣做,因為默認行為是查找以Validator為后綴的相同 Constraint 名稱(即PhoneNumberValidator )。

另一個原因可能是調用ValidatorInterface validate方法。 也許您正在傳遞一些驗證組(如果您可以在此處與我們共享該部分),在這種情況下,您需要在注釋@CustomAssert\\PhoneNumber(groups={"some_group"})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM