0

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?

1
  • Post the HTML of the form, you are relying on form classes to specify validation rules, so we need to see those. See the demo code here. docs.jquery.com/Plugins/Validation Commented Oct 4, 2011 at 19:27

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.