使用jquery验证插件,如果我第一次提交表单时出现错误,那么它将不允许表单提交并显示错误。但是,如果我只修复了一个表单元素错误并使其他元素仍然无效,则表单将提交到表单操作URL。
我希望表单不提交,除非用户已修复所有错误。我试图在submithandler中返回false但是徒劳无功。
jQuery(function ($) {
$('#regform').validate({
rules: {
fullname: {
required: true,
minlength: 2,
maxlength: 20,
lettersonly: true
},
gender: {
required: true
},
mobile: {
required: true,
minlength: 10,
maxlength: 13,
digits: true
},
address: {
required: true,
minlength: 10,
},
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 6
}
},
messages: {
fullname: {
required: "Please enter your full name",
minlength: "Name should be more than 2 characters",
maxlength: "Name should be less than 20 characters",
lettersonly: "Name should contain only letters"
},
gender: {
required: "Please select your gender",
},
mobile: {
required: "Please enter your mobile number",
minlength: "Mobile number should be more than 10 characters",
maxlength: "Mobile number should be less than 13 characters",
digits: "Mobile number should contain only digits"
},
address: {
required: "Please enter your address",
minlength: "Address should be more than 10 characters",
},
email: {
required: "Please enter your email address",
email: "Please enter a valid email address"
},
password: {
required: "Please provide a password",
minlength: "password must be at least 6 characters"
}
},
submitHandler: function(form) {
var valid = $("regform").valid();
if(!valid) {
e.preventDefault();
alert("stop");
} else {
e.preventDefault();
}
}
});
});
答案 0 :(得分:1)
使用类似的设置,但字段较小 - https://codepen.io/jefftimbre/pen/xWjQrX?editors=1010
lettersonly
方法可能已被删除或弃用。将以下内容添加到您的代码中,它应该可以工作。让我知道。
$.validator.addMethod( "lettersonly", function( value, element ) {
return this.optional( element ) || /^[a-z]+$/i.test( value );
}, "Letters only please" );
答案 1 :(得分:0)
您是否尝试在submithandler中将var valid = $("regform").valid();
修改为
var valid = $("#regform").valid();
?
让我知道修改后的情况。我可以帮助你进一步研究这个问题。