JSFiddle - React, Tailwind, and code Playground

by Yurii Shpylovyi

HTML

<input type="text" id="youTubeUrl" />
<input type="button" value="Validate" onclick="validateYouTubeUrl()">
<iframe id="videoObject" type="text/html" width="500" height="265" frameborder="0" allowfullscreen></iframe>

JavaScript

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);
        console.log(match[2]);
        if (match && match[2].length == 11) {
            // Do anything for being valid
            // if need to change the url to embed url then use below line            
            $('#videoObject').attr('src', 'https://www.youtube.com/embed/' + match[2] + '?autoplay=1&enablejsapi=1');
        } else {
            alert('not valid');
            // Do anything for not being valid
        }
    }
}