我正在使用Jquery验证引擎(https://github.com/posabsolute/jQuery-Validation-Engine)作为我的一个表单。验证工作正常,但即使字段值不符合验证,也无法阻止表单提交:
我有一份时事通讯Sigunp表格如下:
<form id="submit-newsletter" method="POST" action="">
<input type="text" class="searchform validate[required, custom[email]]" value="Enter Your Email" id="email" name="nw-email" onblur="defaultInput(this);" onfocu s="clearInput(this);" />
<input type="hidden" id="newsletter" name="newsletter" value="nl" />
<input type="submit" class="submit" title="Signup" value="Sign Up" name="newsletter-signup" onclick="newsletterSubscribe(event);" />
</form>
此表格通过ajax提交如下:
// Newsletter Subscription Without Refresh
function newsletterSubscribe(e) {
e.preventDefault();
var dataString = 'nw-email=' + $('input[name=nw-email]').val() + '&newsletter=' + $('input[name=newsletter]').val();
$.ajax({
type: "POST",
url: "/newsletter/",
data: dataString,
success: function () {
$('#newsletter-box').html('<div id="message"></div>');
$('#message').html('<img width="18px" height="18px" src="/static/img/smtick.png" /><h5>Thank You !</h5>')
.append('<p>We have recieved your request. Please Check your mail for activation instructions. You will start recieving our newsletter once you have verified t his email address.</p>')
.hide()
.fadeIn(1200);
}
});
return false;
}
验证触发器如下:
$(document).ready(function() {
$('#submit-newsletter').validationEngine();
});
现在我可以看到验证错误消息,但如果我按下提交按钮,则无论值是否为电子邮件地址,都会提交表单。
任何想法?
答案 0 :(得分:10)
将代码移动到click事件处理程序并使用jquery绑定它。然后使用验证引擎验证方法测试您的表单是否有效。
$(function(){
$('#newsletter-signup').click(function(e){
e.preventDefault();
//if invalid do nothing
if(!$("#submit-newsletter").validationEngine('validate')){
return false;
}
var dataString = 'nw-email=' + $('input[name=nw-email]').val() + '&newsletter=' + $('input[name=newsletter]').val();
$.ajax({
type: "POST",
url: "/newsletter/",
data: dataString,
success: function () {
$('#newsletter-box').html('<div id="message"></div>');
$('#message').html('<img width="18px" height="18px" src="/static/img/smtick.png" /><h5>Thank You !</h5>')
.append('<p>We have recieved your request. Please Check your mail for activation instructions. You will start recieving our newsletter once you have verified t his email address.</p>')
.hide()
.fadeIn(1200);
}
});
return false;
})
});
答案 1 :(得分:1)
如果你把提交放在表单中,它会尝试提交,无论你的验证是什么..它主要发生在mozilla中..
尝试将提交置于表单之外
<form id="submit-newsletter" method="POST" action="">
<input type="text" class="searchform validate[required, custom[email]]" value="Enter Your Email" id="email" name="nw-email" onblur="defaultInput(this);" onfocu s="clearInput(this);" />
<input type="hidden" id="newsletter" name="newsletter" value="nl" />
</form>
<input type="submit" class="submit" title="Signup" value="Sign Up" name="newsletter-signup" onclick="newsletterSubscribe(event);" />
甚至你可以在表单外面提交一个提交按钮..
<button class="submit" title="Signup" value="Sign Up" name="newsletter-signup" onclick="newsletterSubscribe(event);" />
希望这有效:)