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
isValidUrl(java. lang. String) to check if url is valid. And then you can check if url contains Youtube string.
You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.
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/
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With