Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate youtube video ids?

I want to validate youtube video ids sbumitted in the URL to one of my sites before accessing the Youtube API, but I don't know what the allowed characters are in such an id. I see people on the net guessing it can contain numbers and characters, but I haven't yet seen an official specification of these video ids.

Is there one?

like image 289
Tom Avatar asked Apr 30 '10 06:04

Tom


People also ask

How do I verify a YouTube video ID?

you can hit this: http://gdata.youtube.com/feeds/api/videos/VIDEO_ID (Page now returns: "No longer available".) There's no way you can check the validity of the ID with RegEx, since not all alpha-numeric values are valid ID's.

How do I verify my YouTube URL?

Validate Youtube URL with JavaScript Regex(?:www\.)? checks for the www part of the URL. (?:youtu\. be\/|youtube\.com\/ checks for the youtube.com or youtub.be URLs.

Are YouTube video IDs random?

More videos on YouTube Every YouTube video has a unique ID based on a counting system called Base 64. Randomly generated, that Base 64 ID allows YouTube to have a unique yet short url by using the alphabet in lowercase and uppercase plus two symbols: – and _.

Are YouTube video IDs the same length?

The individual characters come from a set of 64 possibilities (A-Za-z0-9_-). 64^11 is somewhat more than 2^64. (10 characters would not be enough.) So basically each youtube ID is actually a 64bit number.


2 Answers

See this thread for official info.

you can hit this: http://gdata.youtube.com/feeds/api/videos/VIDEO_ID (Page now returns: "No longer available".)

and determine if the video is valid based on response

There's no way you can check the validity of the ID with RegEx, since not all alpha-numeric values are valid ID's.

p.s. i'm pretty sure i saw "dashes" in video ID's

p.p.s. "underscore" is a valid character also: http://www.youtube.com/watch?v=nrGk0AuFd_9

[a-zA-Z0-9_-]{11} is the regex (source), but there's no guarantee that the video will be there even if regex is valid

like image 195
roman m Avatar answered Sep 20 '22 20:09

roman m


With v3 of the YouTube API I achieved this by calling:

GET https://www.googleapis.com/youtube/v3/videos?part=id&id=Tr5WcGSDqDg&key={YOUR_API_KEY} 

This returns something like:

{   "kind": "youtube#videoListResponse",   "etag": "\"dc9DtKVuP_z_ZIF9BZmHcN8kvWQ/P2cGwKgbH6EYZAGxiKCZSH8R1KY\"",   "pageInfo": {     "totalResults": 1,     "resultsPerPage": 1   },   "items": [{     "kind": "youtube#video",     "etag": "\"dc9DtKVuP_z_ZIF9BZmHcN8kvWQ/Rgd0_ApwigPcJHVX1Z2SIQ5FJtU\"",     "id": "Tr5WcGSDqDg"   }] } 

So you can just do a check:

if(json.hasOwnProperty('pageInfo') && json.pageInfo.totalResults === 1) {    if(items[0].kind==='youtube#video') {       //valid video ID    } } 
like image 20
richwol Avatar answered Sep 19 '22 20:09

richwol