1.先引入form.js
文件(在使用form.js前需要先引入query.js
文件)
2.通过$('form')
的ajaxSubmit({})
方法来调用form插件
3.$('form').ajaxSubmit({})
配置和ajax的配置基本一直;
4.form.js
把表单中的数据提前封装好了,不要在配置表单中的数据,直接提交即可(一般表单中的值通过name属性来匹配)
1.先引入jquery.validate.min.js
,validate-methods.js
:为扩展的验证规则,messages_zh.min.js
: 为验证提示文件;(在使用form.js前需要先引入query.js
文件)
2.$(form).validate({})方法来配置验证规则
3.$.validate.setDefaults({});配置validate的默认项
4.在$.validate.setDefaults({submitHandler:function(form){
验证后得表单提交配置}});
5.submitHandler:验证规则通过后提交字段,可以在validate方法中配置,也可以在setDefaults中配置
6.常见的字段规则和规则提示字段有
1.登陆表单
<form role="form" id="quickForm">
<div class="card-body">
<div class="form-group">
<label for="exampleInputEmail1">邮箱账户</label>
<input type="email" name="email" class="form-control" id="exampleInputEmail1" placeholder="请输入你的账户邮箱">
</div>
<div class="form-group">
<label for="exampleInputPassword1">密码</label>
<input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="请输入你的密码">
</div>
<div class="form-group">
<label for="exampleInputPassword1">验证码</label>
<div style="display:flex;">
<input type="text" name="captcha" class="form-control" style="width:40%;" id="exampleInputCaptcha" placeholder="验证码">
<img style="width:50%; height: 38px;margin-left: 10px;" onclick="getcapache()" src="{:url('login/verify')}" alt="验证码">
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary form-control">登陆</button>
</div>
</form>
2.表单验证
$(document).ready(function() {
$.validator.setDefaults({
submitHandler: function() {
// alert("表单前端验证通过!");
$("#quickForm").ajaxSubmit({
url: "{:url('/admin/login/index')}",
dataType: null,
type: "POST",
success: function(res) {
// console.log(JSON.parse(res));
res = JSON.parse(res);
if (res["code"]) {
layer.msg(res["msg"], {
// skin: 'layui-layer-lan',
icon: 3
});
} else {
layer.confirm("确定登陆?", {
btn: ['确定'] //按钮
}, function() {
layer.msg(res["msg"], {
icon: 1
});
window.location.href = "{:url('/admin/index/index')}";
});
}
}
});
}
});
$('#quickForm').validate({
rules: {
email: {
required: true,
email: true,
},
password: {
required: true,
minlength: 6
},
captcha: {
required: true,
remote: {
url: 'checkverify',
type: 'POST'
}
}
},
messages: {
email: {
required: "账号不能为空",
email: "账户必须为邮箱"
},
password: {
required: "密码不能为空",
minlength: "密码不能少于6位"
},
captcha: {
required: "验证码不能为空",
remote: "验证码不正确"
}
},
errorElement: 'span',
errorPlacement: function(error, element) {
error.addClass('invalid-feedback');
element.closest('.form-group').append(error);
},
highlight: function(element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass('is-invalid');
}
});
});