How to validate a YouTube url using JavaScript

validate a YouTube url using JavaScript

Here is a little code snippet to help you validate a value to ensure it's a YouTube url using JavaScript.

This regex here will ensure that the url supplied matches the criteria of a valid youtube url:

  • This is that it is from www.youtube.com or youtu.be
  • That it contains either a 'v=' querystring or has the id as part of the url supplied
  • It also makes sure that the id is 11 characters long.
function validateYouTubeUrl(urlToParse){
                if (urlToParse) {
                    var regExp = /^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
                    if (url.match(regExp)) {
                        return true;
                    }
                }
                return false;
            }

blog comments powered by Disqus

Get In Touch

Follow me online at TwitterFacebook or Flickr.

You can also contact me by email.

Buy Me A Coffee

Latest Tweets


Buy Me A Coffee