Reputation: 21877
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?
Upvotes: 0
Views: 351
Reputation: 457
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.
Upvotes: 1
Reputation: 294
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
Upvotes: 0
Reputation: 7133
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.
Upvotes: 0