jquery.validate默认验证方式为submit时,有时候需要用ajax提交表单,完整代码:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
<form id="form">
<div>
<input type="text" name="name">
</div>
<button id="submit-btn">保存</button>
</form>
</body>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
<script type="text/javascript">
$(function () {
function validateName() {
return $("#form").validate({
rules:{
name:{
required: true
}
},
message:{
name:{
required: '这是必填字段'
}
},
errorPlacement: function(error, element) {
error.appendTo(element.parent())
}
}).form();
};
$("#submit-btn").on("click",function () {
if( validateName() ) {
// ajax提交
}
})
})
</script>
</html>