需要用到一個插件WxValidat.js
在需要使用的page js文件下導入
1
|
import WxValidate from '../../utils/WxValidate.js' |
主要內容
WXML內容
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 = "請輸入用戶名" /> </ 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內容
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
|
/** * 生命周期函數--監聽頁面加載 */ onLoad: function (options) { this .initValidate() //驗證規則函數,初始化字段規則和字段提示信息 }, initValidate() { const rules = { userName: { //用戶名 required: true , minlength:2 }, password: { //密碼 required: true }, phone:{ //手機號 required: true , tel: true } } const messages = { //提示信息 userName: { required: '請填寫姓名' , minlength: '請輸入正確的名稱' }, password: { required: '請填寫密碼' }, 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] console.log(error); return false } console.log( "yes" ); return true ; }, |
值得注意的是: WxValidate的errorList列表返回的是一個對象。
而且驗證的字段名應該和表單組件對應的name一一對應。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/weixin_45750972/article/details/116033297