微信小程序的表單驗(yàn)證,供大家參考,具體內(nèi)容如下
需要用到一個(gè)插件WxValidat.js
在需要使用的page js文件下導(dǎo)入
1
|
import WxValidate from '../../utils/WxValidate.js' |
主要內(nèi)容
WXML內(nèi)容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
< 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 = "請(qǐng)輸入用戶名" /> </ 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 = "請(qǐng)輸入密碼" /> </ view > </ view > < view class = "weui-cells__title" >手機(jī)號(hào)</ 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 = "請(qǐng)輸入手機(jī)號(hào)" /> </ view > </ view > < view class = "btn-area" > < button formType = "submit" >Submit</ button > < button formType = "reset" >Reset</ button > </ view > </ form > |
js內(nèi)容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
/** * 生命周期函數(shù)--監(jiān)聽(tīng)頁(yè)面加載 */ onLoad: function (options) { this .initValidate() //驗(yàn)證規(guī)則函數(shù),初始化字段規(guī)則和字段提示信息 }, initValidate() { const rules = { userName: { //用戶名 required: true , minlength:2 }, password: { //密碼 required: true }, phone:{ //手機(jī)號(hào) required: true , tel: true } } const messages = { //提示信息 userName: { required: '請(qǐng)?zhí)顚?xiě)姓名' , minlength: '請(qǐng)輸入正確的名稱' }, password: { required: '請(qǐng)?zhí)顚?xiě)密碼' }, phone:{ required: '請(qǐng)?zhí)顚?xiě)手機(jī)號(hào)' , tel: '請(qǐng)?zhí)顚?xiě)正確的手機(jī)號(hào)' } } this .WxValidate = new WxValidate(rules, messages) }, //調(diào)用驗(yàn)證函數(shù) formSubmit: function (e) { console.log( 'form發(fā)生了submit事件,攜帶的數(shù)據(jù)為:' , e.detail.value) const params = e.detail.value //校驗(yàn)表單 if (! this .WxValidate.checkForm(params)) { const error = this .WxValidate.errorList[0] console.log(error); return false } console.log( "yes" ); return true ; }, |
值得注意的是: WxValidate的errorList列表返回的是一個(gè)對(duì)象。
而且驗(yàn)證的字段名應(yīng)該和表單組件對(duì)應(yīng)的name一一對(duì)應(yīng)。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/weixin_45750972/article/details/116033297