简体   繁体   中英

JQuery validate() method plugin with JS submit

I have the following code:

<a href="#" onclick="submit_form('http://allstateagents.contextoptional.com//create_lead'); return false;"><img alt="Btn_requestaquote" src="http://a0.allstateagents.contextoptional.com/images/btn_requestAquote.png?1317752211"></a>

which corresponds to:

function submit_form(posturl) {
    $.ajax({
      url: '/create_lead',
      data: {
        'lead_gen[promotion_id]': $('#lead_gen_promotion_id').val(),
        'lead_gen[name]': $('#lead_gen_name').val(),
        'lead_gen[email]': $('#lead_gen_email').val(),
      },
      type: 'POST',
      dataType: 'json',
      success: function(data) {
        console.log(data)
         $('#content').html(data.html);
      }
    });

I call validate and my form, skips validation and goes straight to the post method. I know that validate() is working because I use an event to call validations in line.

$(document).ready(function(){
    $("#lead_gen_email").validate();
    console.log("testing validate")


    $("#lead_gen_email").validate({
       onkeyup: true
    })

  });
   }

Am I doing something wrong? How can I fix this?

That's because you've attached the ajax post to onClick. It fires the ajax regardless of the validation script. Use something like

$('#yourlink').click(function(e){
 if (aVariableThatIndicatesPresenceOfErrors) {
  e.preventDefault()
 } else {
  submit_form(posturl)
 }

})

Of course, that variable will have to be made somehow. Perhaps a selector with the error message class?

var hasError = $('div.error').length;

Not sure if the validate plugin has a callback method though, which could negate all this.

You would need to actually use the form's submit event to automatically validate. Your code simply posts to the server via ajax w/o ever validating anything.

You can use the following code:

function submit_form(posturl) {
if ($("#targetFormId").valid()) {
$.ajax({
  url: '/create_lead',
  data: {
    'lead_gen[promotion_id]': $('#lead_gen_promotion_id').val(),
    'lead_gen[name]': $('#lead_gen_name').val(),
    'lead_gen[email]': $('#lead_gen_email').val(),
  },
  type: 'POST',
  dataType: 'json',
  success: function(data) {
    console.log(data)
     $('#content').html(data.html);
  }
}
});

Replace "targetFormId" with your form id

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