How to validate Youtube and Vimeo URLs

6.5k Views Asked by At

I have to created this fiddle which only validate youtube url. I want to validate also vimeo links with same input , Is it possible to do ?

Here is my js code ;

function ytVidId(url) {
    var p = /^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
    return (url.match(p)) ? RegExp.$1 : false;
}

$('#youtube').bind("change keyup input", function() {
    var url = $(this).val();
    if (ytVidId(url) !== false) {
        $("#status").html('<iframe src="https://www.youtube.com/embed/' + ytVidId(url) + '" id="videoObject" type="text/html" width="100%" height="265" frameborder="0" allowfullscreen></iframe>');
        $('#button').attr('disabled', false);

    } else {
        $("#status").html("not valid url");
        $('#button').attr('disabled',true);

    }
});
1

There are 1 best solutions below

3
On BEST ANSWER

You can check the validity of url by using below expressions.

   var a= url.match(/http:\/\/(:?www.)?(\w*)/)[2];
   if (a =="youtube")
    { 
           // do stuff
    }
   else if (a =="vimeo")
    {
            // do stuff
    }
    else
    {
           // Not a valid url
    }

or

var a  = url.match("/http:\/\/(?:www.)?(?:(vimeo).com\/(.*)|(youtube).com\/watch\?v=(.*?)&)/");

if (a =="youtube")
{ 
  // do stuff
}
else if (a =="vimeo")
{
// do stuff
}
else
{
    // Not a valid url
}