微信小程序 WeUI·Form

2022-05-12 17:36 更新

Form

Form表單組件,結(jié)合Cell、Checkbox-group、Checkbox組件等做表單校驗(yàn)。

示例代碼:

{
  "component": true,
  "usingComponents": {
    "mp-toptips": "../components/toptips/toptips",
    "mp-cells": "../components/cells/cells",
    "mp-cell": "../components/cell/cell",
    "mp-checkbox": "../components/checkbox/checkbox",
    "mp-checkbox-group": "../components/checkbox-group/checkbox-group",
    "mp-form": "../components/form/form"
  }
}
<mp-toptips msg="{{error}}" type="error" show="{{error}}"></mp-toptips>
<view class="page" xmlns:wx="http://www.w3.org/1999/xhtml">
    <view class="page__hd">
        <view class="page__title">Form</view>
        <view class="page__desc">表單輸入</view>
    </view>
    <view class="page__bd">
        <mp-form id="form" rules="{{rules}}" models="{{formData}}">
            <mp-cells title="單選列表項(xiàng)">
                <mp-checkbox-group prop="radio" multi="{{false}}" bindchange="radioChange">
                    <mp-checkbox wx:for="{{radioItems}}" wx:key="value" label="{{item.name}}" value="{{item.value}}" checked="{{item.checked}}"></mp-checkbox>
                </mp-checkbox-group>
            </mp-cells>
            <mp-cells title="復(fù)選列表項(xiàng)">
                <mp-checkbox-group prop="checkbox" multi="{{true}}" bindchange="checkboxChange">
                    <mp-checkbox wx:for="{{checkboxItems}}" wx:key="value" label="{{item.name}}" value="{{item.value}}" checked="{{item.checked}}"></mp-checkbox>
                </mp-checkbox-group>
            </mp-cells>

            <mp-cells title="表單" footer="底部說明文字底部說明文字">
                <mp-cell prop="qq" title="qq" ext-class="">
                    <input bindinput="formInputChange" data-field="qq" class="weui-input" placeholder="請(qǐng)輸入qq"/>
                </mp-cell>
                <mp-cell prop="mobile" title="手機(jī)號(hào)" ext-class=" weui-cell_vcode">
                    <input bindinput="formInputChange" data-field="mobile" class="weui-input" placeholder="請(qǐng)輸入手機(jī)號(hào)"/>
                    <view slot="footer" class="weui-vcode-btn">獲取驗(yàn)證碼</view>
                </mp-cell>
                <mp-cell prop="date" title="日期" ext-class="">
                    <picker data-field="date" mode="date" value="{{date}}" start="2015-09-01" end="2017-09-01" bindchange="bindDateChange">
                        <view class="weui-input">{{date}}</view>
                    </picker>
                </mp-cell>
                <mp-cell prop="vcode" title="驗(yàn)證碼" ext-class=" weui-cell_vcode">
                    <input bindinput="formInputChange" data-field="vcode" class="weui-input" placeholder="請(qǐng)輸入驗(yàn)證碼"/>
                    <image slot="footer" class="weui-vcode-img" src="../images/vcode.jpg" style="width: 108px"></image>
                </mp-cell>
            </mp-cells>
            <mp-cells title="提交后表單項(xiàng)報(bào)錯(cuò)">
                <mp-cell show-error prop="idcard" title="卡號(hào)" ext-class="">
                    <input bindinput="formInputChange" data-field="idcard" class="weui-input" placeholder="請(qǐng)輸入卡號(hào)"/>
                </mp-cell>
            </mp-cells>
        </mp-form>

        <view class="weui-cells__title">開關(guān)</view>
        <view class="weui-cells weui-cells_after-title">
            <view class="weui-cell weui-cell_switch">
                <view class="weui-cell__bd">標(biāo)題文字</view>
                <view class="weui-cell__ft">
                    <switch checked />
                </view>
            </view>
        </view>

        <view class="weui-cells__title">文本框</view>
        <view class="weui-cells weui-cells_after-title">
            <view class="weui-cell">
                <view class="weui-cell__bd">
                    <input class="weui-input" placeholder="請(qǐng)輸入文本" />
                </view>
            </view>
        </view>

        <view class="weui-cells__title">文本域</view>
        <view class="weui-cells weui-cells_after-title">
            <view class="weui-cell">
                <view class="weui-cell__bd">
                    <textarea class="weui-textarea" placeholder="請(qǐng)輸入文本" style="height: 3.3em" />
                    <view class="weui-textarea-counter">0/200</view>
                </view>
            </view>
        </view>

        <view class="weui-cells__title">選擇</view>
        <view class="weui-cells weui-cells_after-title">
            <view class="weui-cell weui-cell_select">
                <view class="weui-cell__hd" style="width: 105px">
                    <picker bindchange="bindCountryCodeChange" value="{{countryCodeIndex}}" range="{{countryCodes}}">
                        <view class="weui-select">{{countryCodes[countryCodeIndex]}}</view>
                    </picker>
                </view>
                <view class="weui-cell__bd weui-cell__bd_in-select-before">
                    <input class="weui-input" placeholder="請(qǐng)輸入號(hào)碼" />
                </view>
            </view>
        </view>

        <view class="weui-cells__title">選擇</view>
        <view class="weui-cells weui-cells_after-title">
            <view class="weui-cell weui-cell_select">
                <view class="weui-cell__bd">
                    <picker bindchange="bindAccountChange" value="{{accountIndex}}" range="{{accounts}}">
                        <view class="weui-select">{{accounts[accountIndex]}}</view>
                    </picker>
                </view>
            </view>
            <view class="weui-cell weui-cell_select">
                <view class="weui-cell__hd weui-cell__hd_in-select-after">
                    <view class="weui-label">國(guó)家/地區(qū)</view>
                </view>
                <view class="weui-cell__bd">
                    <picker bindchange="bindCountryChange" value="{{countryIndex}}" range="{{countries}}">
                        <view class="weui-select weui-select_in-select-after">{{countries[countryIndex]}}</view>
                    </picker>
                </view>
            </view>
        </view>

        <checkbox-group bindchange="bindAgreeChange">
            <label class="weui-agree" for="weuiAgree">
                <view class="weui-agree__text">
                    <checkbox class="weui-agree__checkbox" id="weuiAgree" value="agree" checked="{{isAgree}}" />
                    <view class="weui-agree__checkbox-icon">
                        <icon class="weui-agree__checkbox-icon-check" type="success_no_circle" size="9" wx:if="{{isAgree}}"></icon>
                    </view>
                    閱讀并同意<navigator url="" class="weui-agree__link">《相關(guān)條款》</navigator>
                </view>
            </label>
        </checkbox-group>

        <view class="weui-btn-area">
            <button class="weui-btn" type="primary" bindtap="submitForm">確定</button>
        </view>
    </view>
</view>
Component({
    data: {
        showTopTips: false,

        radioItems: [
            {name: 'cell standard', value: '0', checked: true},
            {name: 'cell standard', value: '1'}
        ],
        checkboxItems: [
            {name: 'standard is dealt for u.', value: '0', checked: true},
            {name: 'standard is dealicient for u.', value: '1'}
        ],
        items: [
            {name: 'USA', value: '美國(guó)'},
            {name: 'CHN', value: '中國(guó)', checked: 'true'},
            {name: 'BRA', value: '巴西'},
            {name: 'JPN', value: '日本'},
            {name: 'ENG', value: '英國(guó)'},
            {name: 'TUR', value: '法國(guó)'},
        ],

        date: "2016-09-01",
        time: "12:01",

        countryCodes: ["+86", "+80", "+84", "+87"],
        countryCodeIndex: 0,

        countries: ["中國(guó)", "美國(guó)", "英國(guó)"],
        countryIndex: 0,

        accounts: ["微信號(hào)", "QQ", "Email"],
        accountIndex: 0,

        isAgree: false,
        formData: {

        },
        rules: [{
            name: 'radio',
            rules: {required: true, message: '單選列表是必選項(xiàng)'},
        }, {
            name: 'checkbox',
            rules: {required: true, message: '多選列表是必選項(xiàng)'},
        }, {
            name: 'qq',
            rules: {required: true, message: 'qq必填'},
        }, {
            name: 'mobile',
            rules: [{required: true, message: 'mobile必填'}, {mobile: true, message: 'mobile格式不對(duì)'}],
        }, {
            name: 'vcode',
            rules: {required: true, message: '驗(yàn)證碼必填'},
        }, {
            name: 'idcard',
            rules: {required: true, message: 'idcard必填'},
        }]
    },
    methods: {
        radioChange: function (e) {
            console.log('radio發(fā)生change事件,攜帶value值為:', e.detail.value);
    
            var radioItems = this.data.radioItems;
            for (var i = 0, len = radioItems.length; i < len; ++i) {
                radioItems[i].checked = radioItems[i].value == e.detail.value;
            }
    
            this.setData({
                radioItems: radioItems,
                [`formData.radio`]: e.detail.value
            });
        },
        checkboxChange: function (e) {
            console.log('checkbox發(fā)生change事件,攜帶value值為:', e.detail.value);
    
            var checkboxItems = this.data.checkboxItems, values = e.detail.value;
            for (var i = 0, lenI = checkboxItems.length; i < lenI; ++i) {
                checkboxItems[i].checked = false;
    
                for (var j = 0, lenJ = values.length; j < lenJ; ++j) {
                    if(checkboxItems[i].value == values[j]){
                        checkboxItems[i].checked = true;
                        break;
                    }
                }
            }
    
            this.setData({
                checkboxItems: checkboxItems,
                [`formData.checkbox`]: e.detail.value
            });
        },
        bindDateChange: function (e) {
            this.setData({
                date: e.detail.value,
                [`formData.date`]: e.detail.value
            })
        },
        formInputChange(e) {
            const {field} = e.currentTarget.dataset
            this.setData({
                [`formData.${field}`]: e.detail.value
            })
        },
        bindTimeChange: function (e) {
            this.setData({
                time: e.detail.value
            })
        },
        bindCountryCodeChange: function(e){
            console.log('picker country code 發(fā)生選擇改變,攜帶值為', e.detail.value);
    
            this.setData({
                countryCodeIndex: e.detail.value
            })
        },
        bindCountryChange: function(e) {
            console.log('picker country 發(fā)生選擇改變,攜帶值為', e.detail.value);
    
            this.setData({
                countryIndex: e.detail.value
            })
        },
        bindAccountChange: function(e) {
            console.log('picker account 發(fā)生選擇改變,攜帶值為', e.detail.value);
    
            this.setData({
                accountIndex: e.detail.value
            })
        },
        bindAgreeChange: function (e) {
            this.setData({
                isAgree: !!e.detail.value.length
            });
        },
        submitForm() {
            this.selectComponent('#form').validate((valid, errors) => {
                console.log('valid', valid, errors)
                if (!valid) {
                    const firstError = Object.keys(errors)
                    if (firstError.length) {
                        this.setData({
                            error: errors[firstError[0]].message
                        })
    
                    }
                } else {
                    wx.showToast({
                        title: '校驗(yàn)通過'
                    })
                }
            })
        }

    }
});


屬性列表

屬性類型默認(rèn)值必填說明
ext-classstring添加在組件內(nèi)部結(jié)構(gòu)的class,可用于修改組件內(nèi)部的樣式
rulesobject<array>表單校驗(yàn)的規(guī)則列表,格式下面詳細(xì)介紹
modelsobject需要校驗(yàn)的表單的數(shù)據(jù)
bindsuccesseventhandler校驗(yàn)成功觸發(fā)的事件,detail是{trigger},trigger的值是change或validate,表示是輸入改成觸發(fā)的校驗(yàn)還是主動(dòng)調(diào)用的validate接口
bindfaileventhandler校驗(yàn)失敗觸發(fā)的事件,detail是{trigger, errors},trigger的值是change或validate,表示是輸入改成觸發(fā)的校驗(yàn)還是主動(dòng)調(diào)用的validate接口。errors是錯(cuò)誤的字段列表。

rules是表單校驗(yàn)的規(guī)則列表,列表每一項(xiàng)表示一個(gè)字段的校驗(yàn)規(guī)則,注意,必須要在Cell或Checkbox-group組件聲明prop屬性,表單校驗(yàn)規(guī)則才生效,表單校驗(yàn)規(guī)則的定義如下:

屬性類型默認(rèn)值必填說明
namestring校驗(yàn)的字段名
rulesarray/object校驗(yàn)的規(guī)則,如果有多項(xiàng),則是數(shù)組
rules.messagestring校驗(yàn)失敗時(shí)候提示的文字
rules.validatorfunction自定義校驗(yàn)函數(shù),接受rule, value, param, models四個(gè)參數(shù),其中rule格式為{name: '字段名', message: '失敗信息'}, value是字段值,param是校驗(yàn)參數(shù),models是form組件的models屬性。函數(shù)返回錯(cuò)誤提示,表示校驗(yàn)失敗,錯(cuò)誤提示會(huì)通過回調(diào)返回給開發(fā)者
rules.[rule]stringrule是變量,表示內(nèi)置的校驗(yàn)規(guī)則名稱,比如required,則校驗(yàn)規(guī)則對(duì)象為{name: "fieldName", rules: {required: true}},下面會(huì)詳細(xì)介紹所有的內(nèi)置規(guī)則

內(nèi)置校驗(yàn)規(guī)則

規(guī)則名參數(shù)說明
required是否必填
minlengthnumber最小長(zhǎng)度
maxlengthnumber最大長(zhǎng)度
rangelength[number, number]長(zhǎng)度范圍,參數(shù)為[最小長(zhǎng)度, 最大長(zhǎng)度]
bytelengthnumber字節(jié)長(zhǎng)度
range[number, number]數(shù)字的大小范圍
minnumber最小值限制
maxnumber最大值限制
mobile手機(jī)號(hào)碼校驗(yàn)
email電子郵件校驗(yàn)
urlURL鏈接地址校驗(yàn)
equalTostring相等校驗(yàn),參數(shù)是另外一個(gè)字段名

接口

validate

validate接口接受類型為function的callback,callback有isValid和errors兩個(gè)參數(shù),isValid表示是否校驗(yàn)通過,errors在校驗(yàn)失敗的時(shí)候的值為失敗的字段列表。

validateField

validateField接口接受2個(gè)參數(shù), 第一個(gè)是字段名,第二個(gè)是類型為function的callback,callback有isValid和errors兩個(gè)參數(shù),isValid表示是否校驗(yàn)通過,errors在校驗(yàn)失敗的時(shí)候的值為失敗的字段列表。

Slot

名稱描述
默認(rèn)內(nèi)容slot


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)