最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

小程序表單校驗(yàn)uni-forms的正確使用方式以及避坑指南

 更新時(shí)間:2022年08月02日 15:58:31   作者:iamlujingtao  
因微信小程序上沒有自帶表單驗(yàn)證,為了實(shí)現(xiàn)就自己做了個(gè)表單驗(yàn)證,下面這篇文章主要給大家介紹了關(guān)于小程序表單校驗(yàn)uni-forms的正確使用方式以及避坑指南,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下

一、前言

小程序上使用表單理應(yīng)是很常用,也很必須的功能,因?yàn)橄到y(tǒng)實(shí)用了uni-app,所以這時(shí)候會(huì)用到uni-forms,但使用過程中遇到不少問題。
這邊的需求有3個(gè):

即時(shí)校驗(yàn)(輸入框失焦立即校驗(yàn)值)需自定義校驗(yàn)規(guī)則需要異步校驗(yàn)

滿足這3個(gè)需求,就能實(shí)現(xiàn)絕大部分表單校驗(yàn),然而直接使用官方的案例并不能滿足,踩過不少坑,最后解決方案如下。

二、成果展示

以下展示均滿足上述3個(gè)需求,下面示例代碼可以直接看 第六點(diǎn)

三、uni-forms即時(shí)校驗(yàn)

實(shí)現(xiàn)即時(shí)校驗(yàn),uni-forms需要加validate-trigger="bind",同時(shí)input添加@blur="binddata('字段名', $event.detail.value)"
示例:

 <uni-forms ref="form" :modelValue="ruleForm" validate-trigger="bind">
   <uni-forms-item label="賬號(hào)" name="account">
     <input v-model.trim="ruleForm.account" 
     @blur="binddata('account', $event.detail.value)" 
     placeholder="請輸入您的登錄賬號(hào)" />
   </uni-forms-item>
 </uni-forms>

四、uni-forms自定義校驗(yàn)規(guī)則

需要自定義校驗(yàn)規(guī)則時(shí),去掉uni-forms的:rules,同時(shí)onReady里加this.$refs.form.setRules(this.rules),其中validateFunction: this.checkEmail為自定義校驗(yàn)方法

示例:

<template>
  <uni-forms ref="form" :modelValue="ruleForm" validate-trigger="bind">
    ......
  </uni-forms>
</template>

<script>
export default {
  data() {
    return {
      // 校驗(yàn)規(guī)則
      rules: {
        email: {
          rules: [
            {
              validateFunction: this.checkEmail,
            },
          ],
        },
      },
    };
  },
  onReady() {
    // 需要在onReady中設(shè)置規(guī)則
    this.$refs.form.setRules(this.rules);
  },
  methods: {
    /**
     * 表單驗(yàn)證郵箱
     */
    checkEmail(rule, value, allData, callback) {
      if (value !== "" && !verifyEmail(value)) {
        return callback("郵箱不正確");
      }
      callback();
    },
  },
};
</script>

五、uni-forms異步校驗(yàn)

通常使用異步方法來校驗(yàn)賬號(hào)是否重復(fù)等,步驟:

  1. 首先需要自定義校驗(yàn)方法validateFunction: this.checkAccount
  2. 然后進(jìn)行常規(guī)的規(guī)則校驗(yàn)
  3. 再進(jìn)行異步方法校驗(yàn)賬號(hào)唯一性
    需要使用Promise,校驗(yàn)通過使用 return resolve()
    校驗(yàn)失敗使用 return reject(new Error('錯(cuò)誤提示信息'))

示例(核心代碼部分):

export default {
  data() {
    return {
      // 校驗(yàn)規(guī)則
      rules: {
        account: {
          rules: [
            {
              required: true,
              errorMessage: '請輸入您的賬號(hào)',
            },
            {
              validateFunction: this.checkAccount,
            },
          ],
        },
      },
    };
  },
  methods: {
    // 表單驗(yàn)證賬號(hào)
    checkAccount(rule, value) {
      return new Promise((resolve, reject) => {
        // 先進(jìn)行規(guī)則校驗(yàn)
        if (value === '' || !verifyAccount(value)) {
          return reject(new Error('只能輸入4-30位英文、數(shù)字、下劃線'))
        }

        // 再進(jìn)行異步校驗(yàn),checkUser為本系統(tǒng)api異步方法,結(jié)合你系統(tǒng)使用你自己的方法
        apiCheckAccount({ account: value })
          .then((data) => {
            if (data.exist) {
              return reject(new Error('賬號(hào)已存在'))
            }
            resolve()
          })
          .catch((err) => {
            return reject(new Error(err.message))
          })
      })
    },
  },

六、完整示例源碼

<template>
  <view class="register">
    <view class="title">最實(shí)用表單校驗(yàn)</view>
    <uni-forms ref="form" :modelValue="ruleForm" validate-trigger="bind" label-width="40">
      <uni-forms-item label="賬號(hào)" name="account">
        <input v-model.trim="ruleForm.account" @blur="binddata('account', $event.detail.value)" placeholder="請輸入您的登錄賬號(hào)" />
      </uni-forms-item>
      <uni-forms-item label="姓名" name="name">
        <input v-model.trim="ruleForm.name" @blur="binddata('name', $event.detail.value)" placeholder="請輸入您的姓名" />
      </uni-forms-item>
      <uni-forms-item class="form-item-center">
        <button type="primary" @click="submit()">注冊</button>
      </uni-forms-item>
    </uni-forms>
  </view>
</template>

<script>
import { apiCheckAccount } from '@/api'
import { verifyAccount, verifyName } from '@/utils'

export default {
  data() {
    return {
      // 表單數(shù)據(jù)
      ruleForm: {
        account: '', // 賬號(hào)
        name: '', // 姓名
      },

      rules: {},
    }
  },
  onReady() {
    this.setRules()
    // 需要在onReady中設(shè)置規(guī)則
    this.$refs.form.setRules(this.rules)
  },
  methods: {
    // 提交表單
    submit() {
      this.$refs.form
        .validate()
        .then(() => {
          uni.showToast({
            title: '注冊成功!',
            duration: 2000,
            icon: 'success',
          })
        })
        .catch((err) => {
          console.log('表單校驗(yàn)失?。?, err)
        })
    },

    // 設(shè)置校驗(yàn)規(guī)則
    setRules() {
      this.rules = {
        account: {
          rules: [
            {
              required: true,
              errorMessage: '請輸入您的賬號(hào)',
            },
            {
              validateFunction: this.checkAccount,
            },
          ],
        },
        name: {
          rules: [
            {
              required: true,
              errorMessage: '請輸入您的姓名',
            },
            {
              validateFunction: this.checkName,
            },
          ],
        },
      }
    },

    // 驗(yàn)證賬號(hào)
    checkAccount(rule, value) {
      return new Promise((resolve, reject) => {
        // 先進(jìn)行規(guī)則校驗(yàn)
        if (value === '' || !verifyAccount(value)) {
          return reject(new Error('只能輸入4-30位英文、數(shù)字、下劃線'))
        }

        // 再進(jìn)行異步校驗(yàn),checkUser為本系統(tǒng)api異步方法,結(jié)合你系統(tǒng)使用你自己的方法
        apiCheckAccount({ account: value })
          .then((data) => {
            if (data.exist) {
              return reject(new Error('賬號(hào)已存在'))
            }
            resolve()
          })
          .catch((err) => {
            return reject(new Error(err.message))
          })
      })
    },

    // 驗(yàn)證姓名
    checkName(rule, value, allData, callback) {
      if (!verifyName(value)) {
        return callback('只能輸入1-30位中英文和數(shù)字')
      }
      callback()
    },
  },
}
</script>

補(bǔ)充:記錄一個(gè)uni-forms表單每輸入一次就自動(dòng)失去焦點(diǎn)的問題

局部代碼:

我之前是在key里面放了個(gè)input變量進(jìn)去了,這確實(shí)也是個(gè)低級(jí)錯(cuò)誤,但是此類問題的原因應(yīng)該大同小異,就是v-for底層map循環(huán)的時(shí)候,key值發(fā)生了變化,導(dǎo)致dom更新,出現(xiàn)這個(gè)問題,去掉不確定性的key值綁定就好了

所以,用key要謹(jǐn)慎??!一不小心找bug就是半天過去了

最后

到此這篇關(guān)于小程序表單校驗(yàn)uni-forms正確使用方式以及避坑指南的文章就介紹到這了,更多相關(guān)小程序表單校驗(yàn)uni-forms內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

阿拉善盟| 弋阳县| 镇安县| 正安县| 喀什市| 黄陵县| 六枝特区| 盐亭县| 龙山县| 澄迈县| 吴堡县| 云阳县| 淮阳县| 金山区| 彰化市| 京山县| 三门峡市| 锡林浩特市| 河池市| 上饶县| 南皮县| 浦县| 宝应县| 夏河县| 克山县| 铜川市| 宁海县| 普安县| 永年县| 信丰县| 疏勒县| 东莞市| 德州市| 平谷区| 桦川县| 合山市| 垣曲县| 将乐县| 吉首市| 泸西县| 中宁县|