How to validate youtube video ids?

Solution 1:

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

Solution 2:

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
   }
}

Solution 3:

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;
}

Solution 4:

I solved this issue in the same way Roman recommended. In my helper:

Be sure to include your requires at the top of the file:

require "net/http"
require "uri"

Then:

def validate_id(youtube_id)
  uri = URI.parse("http://gdata.youtube.com/feeds/api/videos/#{ youtube_id }")
  http = Net::HTTP.new(uri.host, uri.port)
  request = Net::HTTP::Get.new(uri.request_uri)
  response = http.request(request)
  %Q{ #{response.code} }
end

Be sure there is no white space between the brackets in "#{response.code}"

Lastly, compare it to the desired response:

def youtube_data(youtube_id) 
  if validate_id(youtube_id) == "200"
    #video is good code
  else %Q{ Video is no longer valid }
  end
end