zl程序教程

您现在的位置是:首页 >  工具

当前栏目

微信小程序 - 表单验证插件WxValidate使用

微信程序插件 验证 表单 使用
2023-09-11 14:19:06 时间

参考文章

(1)

Github地址:WxValidate

 

 

 

 

1. 拷贝至util目录

 

2.项目引入

 

3.查看wxml匹配规则,通过name

 

 

 4.在js配置规则

 

复制代码
  1 import WxValidate from '../../../utils/WxValidate';
  2 
  3 Page({
  4 
  5   /**
  6    * 页面的初始数据
  7    */
  8   data: {},
  9 
 10   onLoad: function(options) {
 11 
 12     /**
 13      * 4-1(先初始化表单)
 14      */
 15     this.initValidate();
 16   },
 17 
 18 
 19 
 20   showModal(error) {
 21     wx.showModal({
 22       content: error.msg,
 23       showCancel: false,
 24     })
 25   },
 26 
 27 
 28   submitForm(e) {
 29     /**
 30      * 4-3(表单提交校验)
 31      */
 32     const params = e.detail.value
 33     if (!this.WxValidate.checkForm(params)) {
 34       const error = this.WxValidate.errorList[0]
 35       this.showModal(error)
 36       return false
 37     }
 38     /**
 39      * 这里添写验证成功以后的逻辑
 40      * 
 41      */
 42     //验证通过以后->
 43     this.submitInfo(params);
 44   },
 45 
 46   /**
 47    * 表单-提交
 48    */
 49   submitInfo(params) {
 50     // form提交
 51     let form = params;
 52     console.log('将要提交的表单信息:', form);
 53 
 54     wx.showToast({
 55       title: '提交成功!!!!',
 56     })
 57   },
 58 
 59   /**
 60    * 表单-验证字段
 61    */
 62   initValidate() {
 63 
 64     /**
 65      * 4-2(配置规则)
 66      */
 67     const rules = {
 68       name: {
 69         required: true,
 70         rangelength: [2, 4]
 71       },
 72       idcard: {
 73         required: true,
 74         idcard: true,
 75       },
 76       tel: {
 77         required: true,
 78         tel: true,
 79       },
 80       // 配置false可关闭验证
 81       regcode: {
 82         required: false,
 83         minlength: 6
 84       },
 85       assistance: {
 86         required: true,
 87         assistance: true,
 88       },
 89     }
 90     // 验证字段的提示信息,若不传则调用默认的信息
 91     const messages = {
 92       name: {
 93         required: '请输入姓名',
 94         rangelength: '请输入2~4个汉字个汉字'
 95       },
 96       tel: {
 97         required: '请输入11位手机号码',
 98         tel: '请输入正确的手机号码',
 99       },
100       idcard: {
101         required: '请输入身份证号码',
102         idcard: '请输入正确的身份证号码',
103       },
104       regcode: {
105         required: '请输入验证码',
106         minlength: '请输入正确的验证码'
107       },
108       assistance: {
109         required: '请勾选 《顺风男服务协议》'
110       },
111     }
112     // 创建实例对象
113     this.WxValidate = new WxValidate(rules, messages)
114     /**
115      * 也可以自定义验证规则
116      */
117     this.WxValidate.addMethod('assistance', (value, param) => {
118       return this.WxValidate.optional(value) || (value.length >= 1 && value.length <= 2)
119     }, '请勾选 《顺风男服务协议》')
120   }
121 });
复制代码

 

 

5.wxml

复制代码
 1 <form bindsubmit='submitForm'>
 2   <view class="container">
 3     <view class='container-info'>
 4       <view class="man-form-info">
 5         <view class='name'>姓名
 6           <input placeholder='请输入姓名' name="name"></input>
 7         </view>
 8         <view class='idcard'>
 9           身份证号码
10           <input maxlength='18' placeholder='请输入身份证号码' type='idcard' name="idcard"></input>
11         </view>
12 
13         <view class='phone'>
14           手机号码
15           <input maxlength='11' placeholder='请输入手机号码' type='number' bindinput="phoneValue" name="tel"></input>
16         </view>
17       </view>
18     </view>
19 
20     <view class='read-man-pact'>
21       <checkbox-group name="assistance">
22         <checkbox></checkbox>
23         <navigator class='pact'>阅读《顺风男服务协议》</navigator>
24       </checkbox-group>
25     </view>
26 
27     <view class='submit-form-info'>
28       <button form-type='submit'>提交</button>
29     </view>
30 
31   </view>
32 </form>
复制代码

 

wxss

复制代码
  1 page {
  2   font-size: 30rpx;
  3 }
  4 
  5 input:hover {
  6   border-bottom: 2px solid #ddd;
  7 }
  8 
  9 button:active {
 10   opacity: 0.7;
 11 }
 12 
 13 .container-info {
 14   padding: 5%;
 15 }
 16 
 17 .man-form-info {
 18   display: flex;
 19   flex-wrap: wrap;
 20   justify-content: center;
 21 }
 22 
 23 .man-form-info .name, .man-form-info .idcard, .man-form-info .phone,
 24 .man-form-info .regcode {
 25   display: flex;
 26   width: 100%;
 27   flex-wrap: wrap;
 28   margin-top: 2%;
 29 }
 30 
 31 .man-form-info input {
 32   width: 100%;
 33   border-bottom: 1px solid #ddd;
 34 }
 35 
 36 .regcode {
 37   position: relative;
 38 }
 39 
 40 .regcode button {
 41   border-radius: 10rpx;
 42   background-color: #3879d9;
 43   color: #fff;
 44   height: 54rpx;
 45   line-height: 54rpx;
 46   font-size: 23rpx;
 47   width: 300rpx;
 48   margin-top: -2%;
 49 }
 50 
 51 .regcode input {
 52   width: 100%;
 53 }
 54 
 55 .code {
 56   position: relative;
 57   width: 100%;
 58 }
 59 
 60 .code button {
 61   position: absolute;
 62   top: 72rpx;
 63   right: 0;
 64 }
 65 
 66 .self-idcard-info {
 67   margin-top: 15%;
 68   display: flex;
 69   flex-wrap: wrap;
 70   justify-content: center;
 71   width: 100%;
 72   border: 1px dashed #ddd;
 73   padding: 2%;
 74 }
 75 
 76 .f-center {
 77   width: 100%;
 78   display: flex;
 79   justify-content: center;
 80 }
 81 
 82 .picture_list {
 83   padding: 0 7%;
 84 }
 85 
 86 .add-image {
 87   background-color: #ddd;
 88   color: #fff;
 89 }
 90 
 91 .upload_progress {
 92   width: 167rpx;
 93   height: 164rpx;
 94 }
 95 
 96 .apply {
 97   width: 96%;
 98   display: flex;
 99   justify-content: space-between;
100   align-items: center;
101   padding: 2%;
102   border-top: 2px solid #ddd;
103   border-bottom: 2px solid #ddd;
104 }
105 
106 .apply-deposit {
107   font-weight: bold;
108 }
109 
110 .apply-deposit-amount {
111   font-weight: bold;
112   color: #fdd20c;
113 }
114 
115 .apply button {
116   margin: 0;
117   padding: 0;
118   width: 240rpx;
119   height: 60rpx;
120   line-height: 60rpx;
121   color: #fff;
122   background-color: #fdd20c;
123 }
124 
125 .read-man-pact {
126   display: flex;
127   justify-content: center;
128   padding: 2%;
129 }
130 
131 .read-man-pact checkbox-group {
132   display: flex;
133   align-items: center;
134 }
135 
136 .pact {
137   border-bottom: 1px solid #ddd;
138 }
139 
140 .submit-form-info {
141   display: flex;
142   justify-content: center;
143 }
144 
145 .submit-form-info button {
146   background-color: #fdd000;
147   width: 80%;
148   margin: 3% 0;
149 }
复制代码

 

 

效果图(拷贝上面的代码即可运行)

 

(2)

微信小程序的开发框架个人感觉大体上跟VUE是差不多的,但是他的表单组件没有自带的验证功能,因此开发小程序的表单验证时候一般有两种方法,一是自己裸写验证规则,但是需要比较扎实的正则表达式基础,一种是利用官方社区开发的WxValidate插件进行表单验证。

WxValidate插件是参考 jQuery Validate 封装的,为小程序表单提供了一套常用的验证规则,包括手机号码、电子邮件验证等等,同时提供了添加自定义校验方法,让表单验证变得更简单。

首先插件的下载地址和官方文档都在WxValidate下载地址和文档地址

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

首先引入的方法就是将插件文件拷贝到你所需要的文件目录下

 

之后可以采用局部引用的方式将插件引入到你所需要的页面的JS文件里,具体操作如下

//index.js页面下
import WxValidate from '../../utils/WxValidate.js'
const app = getApp()
Page({
data: {
form: {
name: '',
phone: ''
}
}
})
这里需要注意的是文件路径的写法

/是从根目录开始算起 ./是从引入文件的目录文件开始,此例子中就是index.js所在目录开始算起 ../就是从引入文件的父级目录开始算起,此例子中index文件夹目录,而../../就是从pages所在目录开始算起,如果这个地方的文件路径写错,编译就会报错

之后就是注意在wxml文件中对表单组件的数据绑定,否则无论表单组件如何填写,都无法验证规则。

表单组件的绑定方法如下

//wxml页面下
<form bindsubmit="formSubmit">
<view class="weui-cells__title">请填写个人信息</view>
<view class="weui-cells weui-cells_after-title">
<view class="weui-cell weui-cell_input">
<view class="weui-cell__hd">
<view class="weui-label">姓名</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" name='name' value='{{form.name}}' placeholder="请输入姓名" />
</view>
</view>
<view class="weui-cell weui-cell_input weui-cell_vcode">
<view class="weui-cell__hd">
<view class="weui-label">手机号</view>
</view>
<view class="weui-cell__bd">
<input class="weui-input" name='phone' type='number' value='{{form.phone}}' placeholder="请输入手机号" />
</view>
</view>
</view>
</form>
主要的方法就是在需要验证的input框内加入value值的绑定,其他的组件同理

然后在js文件中加入form表单的绑定

//index.js
Page({
data: {
form: {
name: '',
phone: ''
}
}
})
然后就是最重要的验证规则的书写了

首先要在onLoad函数中加入验证规则函数

// onLoad中有多个函数的写法,onLoad函数内写函数名,函数在onLoad外定义
onLoad() {
this.getuser()
this.initValidate()//验证规则函数
}

//onLoad中只有一个函数的写法
onLoad:function(){
rules:{}
messages:{}
}
此处需要注意的是一定要在js文件中onLoad验证规则,否则编译会报checkform is not a function 

然后是验证规则和报错规则的代码

//报错
showModal(error) {
wx.showModal({
content: error.msg,
showCancel: false,
})
},
//验证函数
initValidate() {
const rules = {
name: {
required: true,
minlength:2
},
phone:{
required:true,
tel:true
}
}
const messages = {
name: {
required: '请填写姓名',
minlength:'请输入正确的名称'
},
phone:{
required:'请填写手机号',
tel:'请填写正确的手机号'
}
}
this.WxValidate = new WxValidate(rules, messages)
},
//调用验证函数
formSubmit: function(e) {
console.log('form发生了submit事件,携带的数据为:', e.detail.value)
const params = e.detail.value
//校验表单
if (!this.WxValidate.checkForm(params)) {
const error = this.WxValidate.errorList[0]
this.showModal(error)
return false
}
this.showModal({
msg: '提交成功'
})
}
 这里我只写了一点字段的验证,官方文档中还包含了很多字段的验证规则,我就不一一写出来了,这里需要注意的是在initValidate()中要实例化对象,至此表单验证就已经完成了

 下面看看演示效果

(3)

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
    })
复制代码

 

 

.