Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
763 views
in Technique[技术] by (71.8m points)

jquery validate - How to make url validation without http ( or add it after validation passed )?

I can't make my custom url validation rule work.

I'm adding new rule:

 jQuery.validator.addMethod("complete_url", function(val, elem) {
// if no url, don't do anything
  return  /((([A-Za-z]{3,9}:(?://)?)(?:[-;:&=+$,w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,w]+@)[A-Za-z0-9.-]+)((?:/[+~%/.w-_]*)???(?:[-+=&;%@.w_]*)#?(?:[w]*))?)/.test(val);
    });
 ...
 $("#new_website").validate({
    rules: {
          url: "complete_url",
         'website[url]': {
            url: true,
            required: true}
           }
        });

but it returns me

   invalid URL

I checked Regex here - http://www.rubular.com/. It is working, but failing it my custom validator.

What I'm doing wrong ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Please don't use regexes for this. Don't even use the same regex that the jQuery validator uses, it may change in the future and you won't be able to take advantage of the updates. This is the way to do this:

$.validator.addMethod('validUrl', function(value, element) {
        var url = $.validator.methods.url.bind(this);
        return url(value, element) || url('http://' + value, element);
    }, 'Please enter a valid URL');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...