views:

27

answers:

2

I've this jquery code, loading a remote page with a parameter from an input text form

$(document).ready(function() {
    $('form').submit(function() {
        $('#result').load("/api.php", {
            'url': $("input:text[name=url]").val()
        });
    });
});

I need to validate the input text, that is a url.

How can I use the Validate plugin to do validation before the submit?

A: 

In your PHP page just return true or an error message, e.g. "This site isn't allowed" (note the difference, true isn't quoted).

Then use the remote rule, like this:

$("form").validate({
  rules: {
    url: {
      remote: "/api.php"
    }
  }
});

By default it'll send one query pair, the element's name (already url) and it's value, exactly what you were passing before. A string is treated as the error message and true is treated as passing validation.

It's worth noting this rule is special, it'll wait on the AJAX request to finish before validation completes, so it's all in the same bucket, not a separate validation process/step.

Nick Craver
A: 

Using the jQuery Validate plugin you can specify the validation on the form as follows;

$('form').validate({
  rules: {
    firstname: "required",
    surname: "required"
  },
  success: function() {
    $('#result').load("/api.php", {
       'url': $("input:text[name=url]").val()
    });
  },
});

Hopefully this will get you started, further information on the various options available can be found at: http://docs.jquery.com/Plugins/Validation

simnom