声明转载自此页面,在此基础上有点小改动
微信小程序之表单验证 - 潇十一郎 - 博客园 (cnblogs.com)
1.打开大佬的这篇博客,复制封装好的类,放到utils文件夹下面,新建一个js文件名字是WxValidate
我将其暴露方式做了小改变
export {WxValidate}
2.在需要使用的页面加载以下js文件,这里使用相对路径
import {WxValidate} from "../../utils/WxValidate.js"
3.在使用之初始化,在onLoad方法中加入以下代码
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.initValidate();
},
4.复制以下代码,作为需要初始化的方法,此方法中有需要验证的字段和自定义验证信息
initValidate() {
//验证规则
let rules = {
//需要验证的字段
truename: {
required: true,
maxlength: 10
},
card: {
required: true,
number: true
}
}
//自定义验证信息
let message = {
truename: {
required: '请输入姓名',
maxlength: '名字不能超过10个字'
},
card: {
required:"请输入",
idcard: "请输入正确的身份证号码"
},
}
//实例化当前的验证规则和提示消息
this.WxValidate = new WxValidate(rules, message);
},
5.复制以下代码作为错误信息的弹出方式
showModal(error) {
wx.showModal({
content: error.msg,
showCancel: false,
})
},
6.在表单提交的方法中加入验证
formSubmit: function (e) {
//获取要验证的内容
let params = e.detail.value;
//console.log(params);
if (!this.WxValidate.checkForm(params)) {
const error = this.WxValidate.errorList[0]
this.showModal(error)
return false
}
//在此写通过后的逻辑
},