How to validate youtube video ids?
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
}
}
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
If you are looking for a quicker and more scalable solution I would say to use REGEX with some logging/fallback for errors to be pro-active if youtube changes their ID in the future.
I've been working with the YouTube API for a while now dealing with millions of videos , looping through them i found this to be the most ideal :
/^[A-Za-z0-9_-]{11}$/
A more detailed example say in PHP:
public static function validId($id) {
return preg_match('/^[a-zA-Z0-9_-]{11}$/', $id) > 0;
}