开发者

How to validate a form by ajax before submit in jQuery?

开发者 https://www.devze.com 2023-01-25 16:47 出处:网络
I\'m doing it this way: ...submit(function() { $.post(...,funct开发者_运维知识库ion() { validate();

I'm doing it this way:

...submit(function() {
    $.post(...,funct开发者_运维知识库ion() {
         validate();
    })
});

But it turns out that the form is submitted directly...


Have a look at the jQuery Validation Plugin.

Here's an example on how it could be used:

$("#myForm").validate({
    rules: {
        command: 'required'
    },

    messages: {
        command: 'Please enter a command.'
    },

    submitHandler: function(form) {
        $(form).ajaxSubmit({
            success: function(data) { /* ... */ },
            url: form.action,
            dataType: 'json'
        });
    }
});


You'll have to grab each element and run it through your validation, then submit the form later.

Use $(id).value (for id-d elements) or yourForm.someElementName.value (for name-d elements, assuming your form is named yourForm).


If you want to AJAXily do server side validation without posting the form to another page, you could do something like this. Instead of binding the validation action to submit, you could instead make your "submit" button just a "button" type, and then bind your validation to it's click event. Once it passes validation, then you can move on.

For instance:

$('#myPseudoSubmitButton').click(function() {  
     // Send the form to the server side for validation  
     $.post('validation_script.php', { form inputs here }, function(data) {  
          if (data.validated) {
               // Perform some functionality that happens when the form validates
          }
          else {
               // Display an error message to the user
          }
     });
}, 'json');

This of course presupposes that your validation script returns JSON-formatted data with a "validated" attribute.


you need to prevent the default form submission

http://api.jquery.com/event.preventDefault/

$("form").submit(function(event){
  event.preventDefault();
  if(valid())
  {
    $.post . . .
  }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消