How to validate youtube url in client side in text box

50,312

Solution 1

Here is the code which validates the youtube url-

function validateYouTubeUrl()
{
    var url = $('#youTubeUrl').val();
        if (url != undefined || url != '') {
            var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;
            var match = url.match(regExp);
            if (match && match[2].length == 11) {
                // Do anything for being valid
                // if need to change the url to embed url then use below line
                $('#ytplayerSide').attr('src', 'https://www.youtube.com/embed/' + match[2] + '?autoplay=0');
            }
            else {
                // Do anything for not being valid
            }
        }
}

Fiddle Url: https://jsfiddle.net/cpjushnn/12/

Solution 2

See this working example:

function matchYoutubeUrl(url) {
    var p = /^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
    if(url.match(p)){
        return url.match(p)[1];
    }
    return false;
}

Updated Fiddle: http://jsfiddle.net/3ouq9u3v/13/

Solution 3

Combining the answers from here, and some modification, I came up with this regexp:

^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(\?\S*)?$

This will match any format, but will mismatch if the id is longer than 11 characters. Also able to add start video tag with the "?" part at the end.

You can test it by pasting it into this

Solution 4

Escape all the forward slashes present in your regex and then put the modified regex within / delimiter without any spaces or comment lines and you don't need to add x modifier.

var re = /^(?:https?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/watch\?v=([^&]+)/m;
Share:
50,312
Hitesh
Author by

Hitesh

On the Journey to become better and better everyday Thank God, I am not where I used to be, i am growing and I am on my way and I am heading toward the ultimate goal :) Aiming to become the best software developer, To develop the best quality and standard products. Love Learning new stuff to improve my skills. "Learning to Soar Like an Eagle…Even When You Feel Like a Chicken" I have just touched the surface of web development, There is so much here and still need to learn swimming :D And As They All Say "You don’t have to be a genius to code!" ;)

Updated on January 02, 2022

Comments

  • Hitesh
    Hitesh over 2 years

    I have to create a text box which only allows you tube url for videos.

    To handle the validation in server side, I am using below code

    $rx = '~
        ^(?:https?://)?              # Optional protocol
         (?:www\.)?                  # Optional subdomain
         (?:youtube\.com|youtu\.be)  # Mandatory domain name
         /watch\?v=([^&]+)           # URI with video id as capture group 1
         ~x';
    
    $has_match = preg_match($rx, $url, $matches);
    

    I was looking for the same solution for client side validation. I found about <input type="url"> here but it seems it is only for html5 browsers.

    Is it possible to do client side validation with text box so that it will be compatible with all browser?

    Thanks

  • Hitesh
    Hitesh about 9 years
    it is working as expected and I am glad you you added the working link .. thank you so much
  • Hitesh
    Hitesh about 9 years
    WOW !!! you even added how to change the url to embed url ... pls provide jsfiddle if possible. Thanks
  • Manik Arora
    Manik Arora about 9 years
    @hitesh, just added the fiddle url as well, try it and mark as answer, if this was it...
  • Hitesh
    Hitesh about 9 years
    if (match && match[2].length == 11) {... whats the logic behind this one i dont understand ... can you please explain ... thanks
  • Manik Arora
    Manik Arora about 9 years
    "match" specifies that the regex has a match with the string or not and the "match[2].length" specifies length of the second parentheses match should always be 11 characters. As youtube urls have 11 character code for the videos and it will remain 11 characters always like this- v=oB1CUxX1JJE or you can see this answer - stackoverflow.com/a/6250619/3748701
  • Hitesh
    Hitesh about 9 years
    Thanks, Now it makes sense :)
  • Jitendra Pancholi
    Jitendra Pancholi about 9 years
    Thanks for sharing the information that RegExp properties are deprecated but I'm surprised why microsoft doesn't mentioned that. I updated my solution now.
  • Hitesh
    Hitesh about 9 years
    Sorry to bother you again and again but just one last question , in your regex expression I dont see any expression added for youtube.com Eg. |youtube\.com\/ but it is still working as expected !!! how ?
  • Manik Arora
    Manik Arora about 9 years
    Actually youtube has several url formats like youtube.com, youtu.be this regular expression will validate and extract the video ID from any YouTube URL including shortened URLs (youtu.be), watch URLS (youtube.com/watch?) and embed URLs (youtube.com/embed?).
  • Hitesh
    Hitesh about 9 years
    Thank you so much for explaining. I have accepted your answer as right answer
  • user3276435
    user3276435 almost 8 years
    @ManikArora [^#\&\?]* It looks like this piece is having some special meaning which I am not able to figure out. Can you please help me?
  • Manik Arora
    Manik Arora almost 8 years
    @Prateek, this means that section should match a single character not present in the list i.e. #, & and ? as these characters have special meaning/use in a URL. You can play more over this here - regex101.com/r/pN5hU5/1
  • ForestG
    ForestG over 6 years
    this will mark "youuuuuuuutube.com/watch?v=furTlhb-990" and other malformatted links valid as well (an replace them with the id from it for embedding correctly though). I recommend the solution below by Jitendra
  • Amir Savand
    Amir Savand over 5 years
    Cleaner version: /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=|\?v=)([^#&‌​?]*).*/