一.使用WxValidate插件进行表单校验
下载地址https://github.com/18622426238/WxValidate.git
1.test.wxml
<!--pages/test/test.wxml-->
<form bindsubmit='formSubmit'>
<view class="subInfo">
<view class="subInfoItem clearfix">
<text class="tag need">校区名称</text>
<input name='name' value='' placeholder='请输入校区名称' placeholder-class='placeholder'></input>
</view>
<view class="subInfoItem clearfix">
<text class="tag">联系电话</text>
<input name='contactphone' value='' placeholder='请输入联系电话' placeholder-class='placeholder'></input>
</view>
</view>
<view class='btnWrap'>
<button class='saveBtn' form-type='submit'>保存</button>
</view>
</form>
2.test.js
//引入js文件 在utils文件夹下
import WxValidate from '../../utils/WxValidate.js'
var validate;
Page({
// 初始化表单校验
initValidate() {
// 创建实例对象
this.validate = new WxValidate({
name: {
required: true,
maxlength: 20
},
contactphone: {
required: true,
tel: true
}
}, {
name: {
required: '请输入校区名称!',
maxlength: '名称不得超过20字!'
},
contactphone: {
required: '请输入联系电话!',
tel: '电话格式不正确!'
}
})
},
data: {
},
onLoad: function (options) {
this.initValidate()
},
formSubmit(e) {
// 校验表单
if (!this.validate.checkForm(e.detail.value)) {
const error = this.validate.errorList[0];
console.log(error)
wx.showToast({
title: `${error.msg} `,
icon: 'none'
})
return false
}
// 保存操作...
}
})