微信小程序?qū)崿F(xiàn)表單驗證
更新時間:2021年04月23日 11:52:00 作者:Harris-H
這篇文章主要為大家詳細介紹了微信小程序?qū)崿F(xiàn)表單驗證,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
微信小程序的表單驗證,供大家參考,具體內(nèi)容如下
需要用到一個插件WxValidat.js
在需要使用的page js文件下導入
import WxValidate from '../../utils/WxValidate.js'
主要內(nèi)容
WXML內(nèi)容
<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內(nèi)容
/** * 生命周期函數(shù)--監(jiān)聽頁面加載 */ onLoad: function (options) { this.initValidate()//驗證規(guī)則函數(shù),初始化字段規(guī)則和字段提示信息 }, initValidate() { const rules = { userName: { //用戶名 required: true, minlength:2 }, password: { //密碼 required: true }, phone:{ //手機號 required:true, tel:true } } const messages = { //提示信息 userName: { required: '請?zhí)顚懶彰?, minlength:'請輸入正確的名稱' }, password: { required: '請?zhí)顚懨艽a' }, phone:{ required:'請?zhí)顚懯謾C號', tel:'請?zhí)顚懻_的手機號' } } this.WxValidate = new WxValidate(rules, messages) }, //調(diào)用驗證函數(shù) formSubmit: function (e) { console.log('form發(fā)生了submit事件,攜帶的數(shù)據(jù)為:', 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一一對應。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
分享兩個手機訪問pc網(wǎng)站自動跳轉(zhuǎn)手機端網(wǎng)站代碼
這篇文章主要介紹了分享兩個手機訪問pc網(wǎng)站自動跳轉(zhuǎn)手機端網(wǎng)站代碼,需要的朋友可以參考下2015-01-01JavaScript中判斷為整數(shù)的多種方式及保留兩位小數(shù)的方法
這篇文章主要介紹了JavaScript中判斷為整數(shù)的多種方式,以及保留兩位小數(shù)的方法,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09