Getting the ID from a YouTube video URL (Field)

26 views
Skip to first unread message

Laurent

unread,
Nov 23, 2020, 4:45:01 AM11/23/20
to Joomla Component Builder
Hello,
I have created a text field to retrieve a URL from youtube but I would like to clean it up and save only the ID of the video in the database.

I have this PHP code :

$pattern = '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i';
 preg_match($pattern, $value, $match);

But I don't know how to add it in a validation rule, does anyone know how to do it?

Thanks.

Laurent

unread,
Nov 23, 2020, 8:17:17 AM11/23/20
to Joomla Component Builder, Laurent
My new code

// CLEAN UP YOUTUBE ID
public function test(\SimpleXMLElement $element, $value, $group = null, Registry $input = null, Form $form = null)
{
$pattern = '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i';
               preg_match($pattern, $value, $match);
              return true;
}

But this has no effect...

Laurent

unread,
Nov 23, 2020, 9:30:25 AM11/23/20
to Joomla Component Builder, Laurent
My new code 

// CLEAN UP YOUTUBE ID
public function test(\SimpleXMLElement $element, $value, $group = null, Registry $input = null, Form $form = null)
{
                 $required = ((string) $element['required'] == 'true' || (string) $element['required'] == 'required');

if (!$required && empty($value))
{
return true;
}
                $pattern = '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i';
                if (preg_match($pattern, $value, $match) == true)
{
                                 return true;
                                 echo $match[1];
}
else
{
return false;
}
}

but it's the same, no effects

Laurent

unread,
Nov 25, 2020, 12:11:26 AM11/25/20
to Joomla Component Builder, Laurent
I found a solution with JS in the field script

jQuery('.js-youtube-vid').on('paste', function () {
    var newval = '';
    $this = jQuery(this);
    setTimeout(function(){ 
        if (newval = $this.val().match(/(\?|&)v=([^&#]+)/)) {
            $this.val(newval.pop());
        } else if (newval = $this.val().match(/(\.be\/)+([^\/]+)/)) {
            $this.val(newval.pop());
        } else if (newval = $this.val().match(/(\embed\/)+([^\/]+)/)) {
            $this.val(newval.pop().replace('?rel=0', ''));
        }
    }, 500);
});

((ewe))yn

unread,
Dec 19, 2020, 4:47:44 PM12/19/20
to Joomla Component Builder, Laurent
We are moving to GitHub Discussions. We will keep this open to give access to old issues, resolved. But please continue conversations on the new github discussions area ;)
Reply all
Reply to author
Forward
0 new messages