skip to Main Content
Javascript Validate Youtube Video URL

Javascript validate Youtube video URL

I am working on WordPress project on that I need to validate Youtube video URL before going to save it. I am using JAVASCRIPT to validate Youtube video URL. Let’s see how to validate Youtube video URL

function validateYouTubeUrl( url )
{
    if (url != undefined || url != '') {
        var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=|\?vi=)([^#\&\?]*).*/;
        var match = url.match(regExp);
        if (match && match[2].length == 11) {
            return true;
        }
        else {
            return false;
        }
    }
}

Validate Youtube video URL

if( !validateYouTubeUrl( 'https://www.youtube.com/watch?v=UF8uR6Z6KLc' ) ){
    // Youtube video URL is not valid
}else{
    // Youtube video URL is valid
}

Test case for above function is below

https://youtu.be/aadfaefsadfw3542345ad?aflwa= adflkaej lkjoij ( false )
https://www.youtube.com/watch?v=_tmA751lb6Q ( true )
https://vimeo.com/adfaasd234fe? a fa  ( false )
https://player.vimeo.com/video/185829586  ( false )
http://vimeo.com/michaelaronson/nutcracker?id=aflwe ( false )
https://youtube.com/v/UF8uR6Z6KLc  ( true )
https://youtube.com/vi/UF8uR6Z6KLc  ( false )
https://youtube.com/?v=UF8uR6Z6KLc ( true )
https://youtube.com/?vi=UF8uR6Z6KLc ( true )
https://youtube.com/watch?v=UF8uR6Z6KLc ( true )
https://youtube.com/watch?vi=UF8uR6Z6KLc ( true )
https://youtu.be/UF8uR6Z6KLc ( true )
https://www.youtube.com/watch?v=UF8uR6Z6KLc ( true )

I hope this function is useful for validating Youtube URL client side.

Saroj

I am a web designer and developer part-time blogger. Write something on some free time. Find my every day thought here :)

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top