11

In Jquery i want to check the specific url from youtube alone and show success status and others i want to skip by stating it as not valid url

var _videoUrl = "youtube.com/watch?v=FhnMNwiGg5M";
if (_videoUrl.contains("youtube.com"))
{
  alert('Valid'); 
} 
else
{ 
  alert('Not Valid');
} 

how to check with contains. or any other option to check the valid youtube url alone.

Max Shawabkeh
  • 37,799
  • 10
  • 82
  • 91
kart
  • 625
  • 3
  • 12
  • 21
  • 1
    What do you mena 'valid'? As in, it's in the URL has the correct format, or there's actually a video at that link? – mpen Feb 13 '10 at 08:25

8 Answers8

11

I found this from the closure library, might be handy:

/**
 * A youtube regular expression matcher. It matches the VIDEOID of URLs like
 * http://www.youtube.com/watch?v=VIDEOID.
 * @type {RegExp}
 * @private
 */
goog.ui.media.YoutubeModel.matcher_ =
    /https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&(?:amp;)?)*v(?:<[A-Z]+>)?=([0-9a-zA-Z\-\_]+))/i;
David Hellsing
  • 106,495
  • 44
  • 176
  • 212
8

Typically, the thing that most people want is the youtube video ID. To simply match this, use the following regex.

var matches = _videoUrl.match(/watch\?v=([a-zA-Z0-9\-_]+)/);
if (matches)
{
    alert('valid');
}

Naturally, the regex could be expanded to include the entire youtube url, but if all you need is the ID, this is the most surefire way I've found.

Soviut
  • 88,194
  • 49
  • 192
  • 260
  • 1
    Don't forget that video ID is always 11 characters long....You must check that the video ID length is of length 11. – Buhake Sindi Feb 13 '10 at 09:44
  • 4
    Good to know, although I tend to allow any length simply because the ID length could change if they run out of IDs. – Soviut Feb 15 '10 at 22:50
  • 1
    Words from a YouTube developer state that they do not guarantee to keep the 11 characters length: [link](http://osdir.com/ml/youtube-api-gdata/2009-10/msg00237.html) – Áxel Costas Pena Nov 04 '13 at 17:27
  • 1
    @ÁxelCostasPena is right - but even if they didnt state so - 52 036 560 683 837 093 888 (52 trilions) seems like a big number but since more and more people are using youtube and more and more people uploadin... and youtube is with us for a long time... we could easily run out of links in this range in a couple of years :) ...(I've considered a-z,A-Z,0-9) – jave.web Mar 03 '14 at 13:32
  • @jave.web right. Even if all 7 billion people would upload one video every minute, it would take about 14000 years, before we run out of 11 digit ids ;) – basilikum Dec 11 '14 at 09:50
  • @basilikum That is not that far... and considering population growth... anyway you should always try to build eternal solutions :P – jave.web Dec 11 '14 at 16:15
  • @jave.web it doesn't sound that much, but if you think about how the world was 14000 years ago, it's hard to imagine that youtube in it's today form, or the application OP is developing, will exist at that point. Also, that number is only a very very generous calculated lower boundary. If you take into account more realistic numbers (100 hours of video uploaded per minute; average video length 4 min) you will get something like 60.000.000.000 year until we run out of ids. So it's not going to happen. – basilikum Dec 12 '14 at 08:41
  • It's probably good to point out that since this is an older answer, it does not account for YouTube's newer shorthand url style e.g. youtu.be/JQ24UHbhFM8 – FoxMulder900 Apr 21 '15 at 06:11
2

You may try using a regular expression:

var url = 'youtube.com/watch?v=FhnMNwiGg5M';
var isyouTubeUrl = /((http|https):\/\/)?(www\.)?(youtube\.com)(\/)?([a-zA-Z0-9\-\.]+)\/?/.test(url);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

I will give some extra :

For both Youtube and Vimeo to checking those IDs are really vaild or not

var GoogleKey = 'XXXXXXXXXX';
function GetVideoById(id) {
    var site = !isNaN(id) ? 'vimeo' : 'youtube';
    var data = false;
    if(site==='youtube') {
        $.ajax({
            async: false,
            url: 'https://www.googleapis.com/youtube/v3/videos?id='+id+'&key='+GoogleKey+'&part=snippet',
            success: function(r) {
                if(r['items'].length) {
                    data = {'type':'youtube','data':r['items'][0]['snippet']};
                }
            }
        });
    } else {
        $.ajax({
            async: false,
            url: 'http://vimeo.com/api/v2/video/'+id+'.json',
            success: function(r) {
                data = {'type':'vimeo','data':r[0]};
            }
        });
    }
    return data;
}

So Example runs :

if(GetVideoById('YykjpeuMNEk')) {
   // youtube + data
}

if(GetVideoById('162334918')) {
   // vimeo + data
}
if(GetVideoById('999999')) {
   // nothing (because false)
}
if(GetVideoById('abcdefg')) {
   // nothing (because false)
}
l2aelba
  • 21,591
  • 22
  • 102
  • 138
0

You can check if URL contains the word "http://www.youtube.com" using .indexOf()

var url = 'http://www.youtube.com/channel/UChh-akEbUM8_6ghGVnJd6cQ';
if (url.indexOf('http://www.youtube.com') > -1) {
  alert( "true");
} else {
  alert( "false");
}
Praveen
  • 55,303
  • 33
  • 133
  • 164
0
you Want to validate your URL:

Please pass the URL in this function then this will give you true OR false
See Function :
<script>
function isValidUrl(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(s);
}

isValidUrl(yourURL);
</script>
Vishnu Sharma
  • 1,357
  • 12
  • 11
0
var regexp = /^(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?(?=.*v=((\w|-){11}))(?:\S+)?$/;

var matches_array = video_url.match(regexp);

if(matches_array == null)

{

                alert("Enter youtube url");

                return false;

}
László Papp
  • 51,870
  • 39
  • 111
  • 135
0

Assuming you want a Youtube video URL rather than any YouTube URL, you can do it using a regex:

var url = 'youtube.com/watch?v=FhnMNwiGg5M';
var matches = url.match(/^(https?:\/\/)?([^\/]*\.)?youtube\.com\/watch\?([^]*&)?v=\w+(&[^]*)?/i);
Max Shawabkeh
  • 37,799
  • 10
  • 82
  • 91