I am using livevalidation to validate a form input field where it asks for a youtube video url and I am trying to create a url rule so that it validates when the user inputs http://www.youtube.com/watch?v=11chars. I tried to combine the partialmatch option in the link above like so:
var link = new LiveValidation('link');
开发者_运维百科link.add( Validate.Inclusion, { within: [ 'http://' , 'www', 'youtube.com/watch?v=' ], partialMatch: true } )
and combine it with this length example:
var link = new LiveValidation('link');
link.add( Validate.Length, { minimum: 50, maximum: 50 } );
but obviously this looks clumsy and I dont think it'll be very effective if it worked properly.
Is there a possible way to combine some of the examples from the link above to validate the youtube url properly? Thanks for the help!
Use Validate.Format
with a regular expression:
link.add(Validate.Format, { pattern: /^http\:\/\/www\.youtube\.com\/watch\?v=[a-z0-9]{11}$/i });
Edit: To validate links with additional query parameters, you can use something like this:
/^http\:\/\/www\.youtube\.com\/watch\?v=[a-z0-9]{11}(&.*)?$/i
link.add(Validate.Format, { pattern: /^http\:\/\/www\.youtube\.com\/watch\?v=[a-zA-Z0-9---_]{11}$/ });
this works! didnt know I could just use regex to do it so I tweaked @gilly3 code a bit
Here's a regex that validates for both your JavaScript & PHP, and does it for three kinds of URLs: the classic (?v=), the AJAXed one (#!v=) and the short version (youtu.be). It also supports international URLs.
/http:\/\/(?:youtu\.be\/|(?:[a-z]{2,3}\.)?youtube\.com\/watch(?:\?|#\!)v=)([\w-]{11}).*/gi
Code snippet found on Snipplr :)
精彩评论