小程序中遇到了表單驗證,剛開始想自己寫一個正則.但是最后還是使用了
WxValidate.js這個東西,他只需要將一個js文件放進你的項目,用的時候引用一下,就可以了.非常的方便.
接下來說一下怎么使用,
1.在github下載WxValidate.js
2.放入你的項目其中一個文件夾下.
3.在需要的頁面引用下
import WxValidate from '../vendor/utils/WxValidate.js'
4. 在onLoad函數中加入
this.initValidate() //驗證規則函數
5.在onLoad同級放入
//報錯 showModal(error) { wepy.showModal({ content: error.msg, showCancel: false }) } //調用驗證函數 formSubmit(e) { const params = e console.log(this.WxValidate, 'params') //校驗表單 if (!this.WxValidate.checkForm(params)) { const error = this.WxValidate.errorList[0] this.showModal(error) return false } return true } //驗證函數方法 initValidate() { const rules = { ProductName: { required: true, minlength: 1 }, Introduce: { required: true, minlength: 1 }, thdata: { required: true, min: 0 }, LendingDays: { required: true, min: 1 } } //函數驗證報錯信息 const messages = { ProductName: { required: '請填寫產品名稱', minlength: '產品名稱不能為空' }, Introduce: { required: '請填寫產品簡介', minlength: '產品簡介不能為空' }, thdata: { required: '請填寫產品的月基准利率', min: '月基准利率只能位數字' }, LendingDays: { required: '請填寫放款天數', min: '放款天數只能為數字' } } this.WxValidate = new WxValidate(rules, messages) }
//需要注意的是messages 中的第一行代表為空時的提示信息.第二行代表沒有符合驗證的提示信息
//所以第二行的參數:如:min等一定要與上邊rules中的第二行的字段保持一致
//如果用的原生小程序,請在input中加入name='字段名'.如果是組件,如wepy等,將value綁定為字段名即可
這段代碼
6.在html中加入
<view class="submitBtn" @tap="submit({{form}})">提交</view>
//這里特別注意一下,觸發的點擊事件中的參數form是一個對象,里面包含了所有需要驗證的字段
7.在submit方法中加入
let flag = this.formSubmit(e) //調用驗證方法 if (!flag) return
//這里e為接受到上面傳過來的form對象