微信小程序 - 表單驗證插件WxValidate使用


插件下載地址及官方文檔:https://github.com/skyvow/wx-extend

具體的WxValidate.js文件的位置在wx-extend/src/assets/plugins/wx-validate/WxValidate.js   

地址: https://github.com/skyvow/wx-extend/tree/master/src/assets/plugins/wx-validate

 

步驟一:將文件 WxValidate.js 拷貝到utils目錄下

 

 步驟二:2種引入方式 =》全局引入: 在app.js中寫以下代碼;局部引入:在需要的js文件下寫以下代碼【這里要寫絕對路徑】

import wxValidate from "./utils/wxValidate";

 

 步驟三:wxml匹配規則,通過name

 wxml 里 input 的name值必須和配置的rules的名稱一致,否則匹配無效

 

 

 步驟三:在js配置規則

import WxValidate from '../../../utils/WxValidate';

Page({
    /*** 頁面的初始數據*/
    data: {},

    onLoad: function(options) {
      
        /*** 4-1(先初始化表單)*/
        
        this.initValidate();
    },

    /*** 表單-驗證字段*/
    initValidate() {
        /*** 4-2(配置規則)*/
        const rules = {
            name: {
                required: true,
                rangelength: [2, 4]
            },
            idcard: {
                required: true,
                idcard: true,
            },
            tel: {
                required: true,
                tel: true,
            },
            // 配置false可關閉驗證
            regcode: {
                required: false,
                minlength: 6
            },
            assistance: {
                required: true,
                assistance: true,
            },
        }
        // 驗證字段的提示信息,若不傳則調用默認的信息
        const messages = {
            name: {
                required: '請輸入姓名',
                rangelength: '請輸入2~4個漢字個漢字'
            },
            tel: {
                required: '請輸入11位手機號碼',
                tel: '請輸入正確的手機號碼',
            },
            idcard: {
                required: '請輸入身份證號碼',
                idcard: '請輸入正確的身份證號碼',
            },
            regcode: {
                required: '請輸入驗證碼',
                minlength: '請輸入正確的驗證碼'
            },
            assistance: {
                required: '請勾選 《順風男服務協議》'
            },
        };
        
        // 創建實例對象
        this.WxValidate = new WxValidate(rules, messages)
        
        /*** 也可以自定義驗證規則*/
        this.WxValidate.addMethod('assistance', (value, param) => {
            return this.WxValidate.optional(value) || (value.length >= 1 && value.length <= 2)
        }, '請勾選 《順風男服務協議》')
    },
    submitForm(e) {
        /***4-3(表單提交校驗)*/
        const params = e.detail.value
        if (!this.WxValidate.checkForm(params)) {
            const error = this.WxValidate.errorList[0]
            this.showModal(error)
            return false
        }
        /*** 這里添寫驗證成功以后的邏輯**/
        
        //驗證通過以后->
        this.submitInfo(params);
    },

    /*** 表單-提交*/
    submitInfo(params) {
        // form提交
        let form = params;
        console.log('將要提交的表單信息:', form);

        wx.showToast({
            title: '提交成功!!!!',
        })
    },

    showModal(error) {
        wx.showModal({
            content: error.msg,
            showCancel: false,
        })
    }
});

 xml

<form bindsubmit='submitForm'>
  <view class="container">
    <view class='container-info'>
      <view class="man-form-info">
        <view class='name'>姓名
          <input placeholder='請輸入姓名' name="name"></input>
        </view>
        <view class='idcard'>
          身份證號碼
          <input maxlength='18' placeholder='請輸入身份證號碼' type='idcard' name="idcard"></input>
        </view>

        <view class='phone'>
          手機號碼
          <input maxlength='11' placeholder='請輸入手機號碼' type='number' bindinput="phoneValue" name="tel"></input>
        </view>
      </view>
    </view>

    <view class='read-man-pact'>
      <checkbox-group name="assistance">
        <checkbox></checkbox>
        <navigator class='pact'>閱讀《順風男服務協議》</navigator>
      </checkbox-group>
    </view>

    <view class='submit-form-info'>
      <button form-type='submit'>提交</button>
    </view>

  </view>
</form>

 

wxss

page {
  font-size: 30rpx;
}

input:hover {
  border-bottom: 2px solid #ddd;
}

button:active {
  opacity: 0.7;
}

.container-info {
  padding: 5%;
}

.man-form-info {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.man-form-info .name, .man-form-info .idcard, .man-form-info .phone,
.man-form-info .regcode {
  display: flex;
  width: 100%;
  flex-wrap: wrap;
  margin-top: 2%;
}

.man-form-info input {
  width: 100%;
  border-bottom: 1px solid #ddd;
}

.regcode {
  position: relative;
}

.regcode button {
  border-radius: 10rpx;
  background-color: #3879d9;
  color: #fff;
  height: 54rpx;
  line-height: 54rpx;
  font-size: 23rpx;
  width: 300rpx;
  margin-top: -2%;
}

.regcode input {
  width: 100%;
}

.code {
  position: relative;
  width: 100%;
}

.code button {
  position: absolute;
  top: 72rpx;
  right: 0;
}

.self-idcard-info {
  margin-top: 15%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  width: 100%;
  border: 1px dashed #ddd;
  padding: 2%;
}

.f-center {
  width: 100%;
  display: flex;
  justify-content: center;
}

.picture_list {
  padding: 0 7%;
}

.add-image {
  background-color: #ddd;
  color: #fff;
}

.upload_progress {
  width: 167rpx;
  height: 164rpx;
}

.apply {
  width: 96%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 2%;
  border-top: 2px solid #ddd;
  border-bottom: 2px solid #ddd;
}

.apply-deposit {
  font-weight: bold;
}

.apply-deposit-amount {
  font-weight: bold;
  color: #fdd20c;
}

.apply button {
  margin: 0;
  padding: 0;
  width: 240rpx;
  height: 60rpx;
  line-height: 60rpx;
  color: #fff;
  background-color: #fdd20c;
}

.read-man-pact {
  display: flex;
  justify-content: center;
  padding: 2%;
}

.read-man-pact checkbox-group {
  display: flex;
  align-items: center;
}

.pact {
  border-bottom: 1px solid #ddd;
}

.submit-form-info {
  display: flex;
  justify-content: center;
}

.submit-form-info button {
  background-color: #fdd000;
  width: 80%;
  margin: 3% 0;
}

 

 

以上轉自:https://www.cnblogs.com/cisum/p/9556736.html,邏輯如上

 

改:

步驟一:將文件 WxValidate.js 拷貝到utils目錄

步驟二:在app.js中引入,並且實例化驗證

//引入wxValidate.js文件
import wxValidate from "./utils/wxValidate";

//創建實例對象
wxValidate: (rules, messages) => new wxValidate(rules, messages),

/**原來是這么實例化的
 this.WxValidate = new WxValidate(rules, messages)**/

步驟三:在wxml中寫

    <form report-submit bindsubmit="loginForm">
            <input class="hide" name="reg_id" value="{{openid}}"/>
            <view class="form-item">
                <i class="iconfont icon-shouji"></i>
                <input type="num"  class="form-input" name="mobile" maxlength="11" value="{{remember.mobile}}" placeholder="請輸入您的郵箱地址"/>
            </view>
            <view class="form-item">
                <i class="iconfont icon-mima"></i>
                <input type="text" password="true" class="form-input" name="password" value="{{remember.password}}" placeholder="請輸入您的密碼"/>
            </view>
            <view class="form-btn">
                <button formType="submit">登錄</button>
            </view>
        </form>

 

步驟四:在js =》 onLoad方法中寫

//配置驗證規則和提示信息, that.WxValidate 是自己定義的這個驗證規則的變量名,也可以是that.WxValidate2
  
var app = getApp()
Page({
 
         
  onLoad: function (options) {
      that.WxValidate = app.wxValidate(
          {
              mobile: {
                required: true,
                tel:true
              },
              password: {
                required: true,
              }
          },
          {
              mobile: {
                  required: '請輸入手機號',
                  tel:'請正確輸入手機號'
              },
              password: {
                  required: '請輸入密碼',
              }
          }
      )
  }
})

 

步驟五:在js =》 loginForm方法中寫 ,這個方法名對應form 的 bindsubmit 事件

form bindsubmit="loginForm"
//表單提交校驗
loginForm: function (e) {
      var that = this;
    //失敗報錯
if (!that.WxValidate.checkForm(e)) { const error = that.WxValidate.errorList[0]; wx.showToast({ title: error.msg, icon: 'none', duration: 2000 }); return false }
    //成功 后登錄接口

}

   

   表單提交校驗結果:

that.WxValidate.errorList

 

form 表單的 的 bindsubmit 事件 傳遞的參數(e)結果如下

 

自定義添加驗證規則,比如要驗證手機號和身份證號同時

寫在需要使用的頁面onLoad

  that.WxValidate = app.wxValidate({
            login_id: {
                required: true,
                telOrCard: true,
            },
            password: {
                required: true
            }
        },
        {
            login_id: {
                required: '請輸入手機號/身份證號',
                telOrCard: '請正確輸入手機號/身份證號',
            },
            password: {
                required: '請輸入密碼'
            }
        })
        
      that.WxValidate.addMethod('telOrCard',(value, param) =>{
        return (/^1[34578]\d{9}$/.test(value) || /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(value))  //匹配見WxValidate.js
      }, '請正確輸入手機號/身份證號')

 

必須添加的要放下面,否則會報錯


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM