简体   繁体   中英

Form Validation with $.post()

I am using bassistance.de's Validation jQuery plugin to validate a form #signup-form . Instead of submitting the form data directly to the server the usual way, the form data should be submitted AJAX'ly via $.post() .

JS Code

// Validate form
$('.signup-form').validate({
    rules: {
        signupName: { required: true, minlength: 3 }
    }
});


// Submit to Serverside
$('#submit-btn').click(function() {
    $.post('/api/register_user',
        $('#signup-modal .signup-form').serialize(),
        success: function() {
            console.log('posted!');
        }
    );
});

Problem: If a user entered data that does not pass the jquery validation, the click handler on #submit-btn will still allow the form to be submitted! Is there a way to check that there are no validation errors?

Try this:

// Validate form
$('.signup-form').validate({
    rules: {
    signupName: { required: true, minlength: 3 }
   }
});


// Submit to Serverside
$('#submit-btn').click(function() {
    if ($('.signup-form').valid()) {
        $.post('/api/register_user',
            $('#signup-modal .signup-form').serialize(),
            success: function() {
                console.log('posted!');
            }
        );
     }
});

The best way to do this is to use the submitHandler option to validate:

$('.signup-form').validate({
    rules: {
        signupName: { required: true, minlength: 3 }
    },
    submitHandler: function(form){
      $.post('/api/register_user',
          $('#signup-modal .signup-form').serialize(),
          success: function() {
              console.log('posted!');
          }
      );
    }
});

This will automatically be called once the form is valid. No need to attach anything new to your submit button or the submit event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM