jQuery Validator – Accept Youtube Videos

I currently do freelance web development for a company named Kyjen. They create fun and innovative dog toys, so I suggest checking them out.

For what I’m working on now, I needed to accept a URL of a Youtube video that the user would submit. I looked into the jQuery Validate plugin and saw that they had the ability to validate if the user submission was a valid URL.

That’s great and all; however, it didn’t prevent people from submitting non-Youtube videos which would be a problem for in the future if we wanted to embed the user submitted videos.

The Validate plugin has the method of adding your own custom methods, and I was able to write my own to only accept valid Youtube URLs. Here’s what I came up with:

jQuery(function() {
  var youtubePattern = /^http:\/\/(?:www\.)?youtube.com\/watch\?(?=.*v=\w+)(?:\S+)?$/i;

  jQuery.validator.addMethod("youtubeVideo", function(value) {
    return youtubePattern.test(value);
  }, "Must be a valid Youtube video");

Update: I’d like to thank one of the members over at the SomethingAwful forums who suggested an even better method. I’ve edited the above to include the new version.

This method can then be used like this:

	rules: {
	    url_field: {
		required: true,
		youtubeVideo: true

I was able to find the regex on this Stack Overflow question thankfully.

Let me know what you guys think and if you have any questions about it.