views:

304

answers:

3

All,

I am trying to use JQuery's URL Validator plugin.

http://docs.jquery.com/Plugins/Validation/Methods/url

I have a text box that has a URL. I want to write a function which takes the textbox value, uses the jquery's validator plugin to validate urls and returns true or false.

Something like Ex:

function validateURL(textval)
{
 // var valid = get jquery's validate plugin return value
  if(valid)
  {
    return true;
  }
  return false;
}

I wanted this to be a reusable function..

Thanks

+2  A: 

The validate() jQuery is made to validate a form itself I believe, not just an individual field.

I think you would be better off using a regex to validate a single textbox if you are not trying to a do a form validation.

Here's an example of a SO question that works.

function validateURL(textval) {
  var urlregex = new RegExp(
        "^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)");
  return urlregex.test(textval);
}

Source: here

gmcalab
A: 

Why don't you just try using JavaScript regular expressions? You don't need a whole plugin just for validating URLs! There are plenty regex's floating about that parse a URL. Just do something like:

if(textval.match(/<regular expression>/)) return true;

Moreover, if using HTML5 is an option, it supports <input type="url"/>, so don't need to worry about validation of URLs at all.

themoondothshine
A: 

You could write a regex, as others have suggested, but it's silly to do it yourself (why reinvent the wheel) and you're probably not going to do as good of a job as the plugin.

Try:

var isValid = function isValid(form, field){
    return $(form).valid({
      rules: {
        field: {
          required: true,
          url: true
        }
      }
    });    
};

Where form is the name of the form, and field is the name of the input in that form. Remove the "required: true" if the field is not required.

This hasn't been tested, but based on the docs you linked to in your question, that should get you on the right track.

Also, not to be a jerk but you should really read the docs more carefully...the answer to your question is in there.

MisterMister