-
需要用到一个插件WxValidat.js
-
在需要使用的page js文件下导入
import WxValidate from '../../utils/WxValidate.js'
-
主要内容
WXML内容
<form bindsubmit="formSubmit">
<view class="weui-cells__title">用户名</view>
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input">
<input class="weui-input" type="text" name="userName" placeholder="请输入用户名"/>
</view>
</view>
<view class="weui-cells__title">密码</view>
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input">
<input class="weui-input" type="text" name="password" placeholder="请输入密码"/>
</view>
</view>
<view class="weui-cells__title">手机号</view>
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input">
<input class="weui-input" type="text" name="phone" placeholder="请输入手机号"/>
</view>
</view>
<view class="btn-area">
<button formType="submit">Submit</button>
<button formType="reset">Reset</button>
</view>
</form>
js内容
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.initValidate()//验证规则函数,初始化字段规则和字段提示信息
},
initValidate() {
const rules = {
userName: { //用户名
required: true,
minlength:2
},
password: { //密码
required: true
},
phone:{ //手机号
required:true,
tel:true
}
}
const messages = { //提示信息
userName: {
required: '请填写姓名',
minlength:'请输入正确的名称'
},
password: {
required: '请填写密码'
},
phone:{
required:'请填写手机号',
tel:'请填写正确的手机号'
}
}
this.WxValidate = new WxValidate(rules, messages)
},
//调用验证函数
formSubmit: function (e) {
console.log('form发生了submit事件,携带的数据为:', e.detail.value)
const params = e.detail.value
//校验表单
if (!this.WxValidate.checkForm(params)) {
const error = this.WxValidate.errorList[0]
console.log(error);
return false
}
console.log("yes");
return true;
},
值得注意的是: WxValidate的errorList列表返回的是一个对象。
而且验证的字段名应该和表单组件对应的name一一对应。