/ Published in: jQuery
Use this snippet to check if user supplied URL is a valid Youtube URL. Has support for youtu.be shortened URL's too.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<script type="text/javascript"> // $('#YTembed') is the ID of your input field $('#YTembed').change(function(){ var txt = $(this).val(); // get the value that the user supplied var flag = false; // Use this flag variable to discern between good and bad entry > Assumes good // First try the normal youtube URL: var arr = txt.split('v='); if (arr.length > 1){ // normal Youtube URL detected var vidcode = arr[1].substr(0,11); // Substring get the 11 characters } else if (txt.indexOf('youtu.be') > -1) { // Normal URL check failed > try the shortened one arr = txt.split('youtu.be'); // Split on shortened URL var vidcode = arr[1].substr(1,11); // Grab the 11 characters from the slash onward } else { // No result > Flag for output flag = true; } if (!flag) $('#vidfeedback').html('<iframe width="580" height="326" src="http://www.youtube.com/embed/'+vidcode+'" frameborder="0" allowfullscreen></iframe>'); else $('#vidfeedback').html("That doesn't appear to be a Youtube URL. Please try again.<br/>We accept the following formats:<br/>http://www.youtube.com/watch?v=XXXXXXXXXXX or <br/>http://youtu.be/XXXXXXXXXXX"); }); </script>