version_improved
version_improved

Reputation: 95

Another way to validate field in Symfony

I write the app in Symfony 3.2. This what I am doing at the moment is writing the add images/youtube videos functionality. The logic of my application is that whether user choices one or the second object, the data is stored in the same database table objects:

And now, while adding video, the link field is validated by this method:

/**
 * Check if link is valid youtube URL.
 * 
 * @Assert\IsTrue(message = "This is not valid....")
 * 
 * @return bool
 */
public function isValidLink() {
    $rx = '~
        ^(?:https?://)?              # Optional protocol
         (?:www\.)?                  # Optional subdomain
         (?:youtube\.com|youtu\.be)/  # Mandatory domain name
         (?:watch\?v=)?             # optional
         (?:[a-zA-Z0-9]{11})          # mandatory
         ~x'
    ;

    return preg_match($rx, $this->link);
}

Of course, there are two separate forms to add each of objects. The problem is that the link field is validated also while adding images.

Therefore, how to validate the link field in such way to keep my present system architecture?

Upvotes: 0

Views: 535

Answers (1)

version_improved
version_improved

Reputation: 95

Ok, I found the solution. The best way to validate my form is to create my custom validator and add it i.e. through the form builder:

$builder->add('link', TextType::class, array(
    'label' => 'Link to the YT video',
    'constraints' => [
        new YouTubeURL(),
    ],
))
// ...

I'll also write the validator files, for posterity :)

AppBundle/Validator/Constraints/YouTubeURL.php:

namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

class YouTubeURL extends Constraint
{
    public $message = 'This is not the valid YouTube URL.';
}

AppBundle/Validator/Constraints/YouTubeURLValidator.php:

namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class YouTubeURLValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        $rx = '~
            ^(?:https?://)?              # Optional protocol
             (?:www\.)?                  # Optional subdomain
             (?:youtube\.com|youtu\.be)/ # Mandatory domain name
             (?:watch\?v=)?              # optional part
             (?:[a-zA-Z0-9]{11})         # mandatory video id
             ~x'
        ;

        if (!preg_match($rx, $value))
        {
            $this->context->buildViolation($constraint->message)
                 ->addViolation();
        }
    }
}

Upvotes: 2

Related Questions