I want to create a custom form validator to check if my user is sending a youtube url.
I’ve already created my lib/validator/youtubeValidator.class.php
Then I use it in my MyForm.class.php : new YoutubeValidator(........)
Here is the code :
class YoutubeValidator extends sfValidatorUrl
{
protected function configure($options = array(), $messages = array())
{
$this->addMessage('invalid', 'Veuillez entrer un lien Youtube');
}
protected function doClean($url)
{
$pattern =
'%^# Match any youtube URL
(?:https?://)? # Optional scheme. Either http or https
(?:www\.)? # Optional www subdomain
(?: # Group host alternatives
youtu\.be/ # Either youtu.be,
| youtube\.com # or youtube.com
(?: # Group path alternatives
/embed/ # Either /embed/
| /v/ # or /v/
| /watch\?v= # or /watch\?v=
) # End path alternatives.
) # End host alternatives.
([\w-]{10,12}) # Allow 10-12 for 11 char youtube id.
$%x'
;
$result = preg_match($pattern, $url, $matches);
if (false !== $result)
{
return $matches[1];
}
return false;
if (false !== $result)
{
throw new sfValidatorError($this, 'invalid', array('value' => $value));
}
else
{
return true;
}
}
}
But it does not work at all.
Moreover, it could be great if my validator could check if youtube video does exist.
You probably need to change the last lines to something like this:
This will only check if the url submitted by user is a youtube url (if it matches your regular expression). If no, will throw an exception.
UPDATE
— deleted–
UPDATE 2
I’ve tested it and seems to be working ok (returning the actual video id when using
$form->getValues()).