简体   繁体   中英

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

I have added the next files:

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();
        }
    }
}

config/validator/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

<?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. 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 ).

An other reason for that is could be the call to validate method of the ValidatorInterface . 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"}) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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