WxValidate插件是參考 jQuery Validate 封裝的,為小程序表單提供了一套常用的驗證規則,包括手機號碼、電子郵件驗證等等,同時提供了添加自定義校驗方法,讓表單驗證變得更簡單。
首先插件的下載地址和官方文檔:https://github.com/skyvow/wx-extend
具體的WxValidate.js文件的位置在wx-extend/src/assets/plugins/wx-validate/WxValidate.js
1、引入方法:將插件文件拷貝到你所需要的文件目錄下
2、采用局部引用的方式將插件引入到你所需要的頁面的JS文件里,具體操作如下
import WxValidate from '../../utils/WxValidate.js'
3、在wxml文件中對表單組件的數據綁定,否則無論表單組件如何填寫,都無法驗證規則。表單組件的綁定方法如下
<view class="issue_item">
<input focus name="title" value="{{title}}" placeholder='請輸入問題描述' />
</view>
主要的方法就是在需要驗證的input框內加入value值的綁定,其他的組件同理
4、驗證規則的書寫。
在onLoad函數中加入驗證規則函數,即驗證規則和報錯規則的代碼
onLoad: function () { // 初始化驗證方法
this.initValidate() },
//報錯
showModal(error) { wx.showModal({ content: error.msg, showCancel: false, }) }, //驗證函數
initValidate() { const rules = { title: { required: true, maxlength: 128 }, dbType: { required: true }, priority: { required: true }, description: { required: true } } const messages = { title: { required: '請輸入問題描述', minlength: '最多只能輸入128個字符' }, dbType: { required: '請選擇問題類型' }, priority: { required: '請選擇問題等級' }, description: { required: '請輸入問題詳情' } } this.WxValidate = new WxValidate(rules, messages) },
5、調用校驗規則
submitIssue (e){ let issueInfo = e.detail.value //校驗表單
if (!this.WxValidate.checkForm(issueInfo)) { const error = this.WxValidate.errorList[0] this.showModal(error) return false } wx.showLoading({ title: '玩命加載中', mask: true })