Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate youtube url in client side in text box

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

like image 395
Hitesh Avatar asked Feb 26 '15 05:02

Hitesh


People also ask

How verify Youtube URL Android?

isValidUrl(java. lang. String) to check if url is valid. And then you can check if url contains Youtube string.

How do you validate a URL?

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.


2 Answers

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/

like image 89
Manik Arora Avatar answered Oct 17 '22 02:10

Manik Arora


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/

like image 27
Jitendra Pancholi Avatar answered Oct 17 '22 03:10

Jitendra Pancholi