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?
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.
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.
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 _.
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.
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
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With