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
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/