小程序表單校驗uni-forms的正確使用方式以及避坑指南
一、前言
小程序上使用表單理應是很常用,也很必須的功能,因為系統(tǒng)實用了uni-app,所以這時候會用到uni-forms,但使用過程中遇到不少問題。
這邊的需求有3個:
即時校驗(輸入框失焦立即校驗值)需自定義校驗規(guī)則需要異步校驗
滿足這3個需求,就能實現(xiàn)絕大部分表單校驗,然而直接使用官方的案例并不能滿足,踩過不少坑,最后解決方案如下。
二、成果展示
以下展示均滿足上述3個需求,下面示例代碼可以直接看 第六點

三、uni-forms即時校驗
實現(xiàn)即時校驗,uni-forms需要加validate-trigger="bind",同時input添加@blur="binddata('字段名', $event.detail.value)"
示例:
<uni-forms ref="form" :modelValue="ruleForm" validate-trigger="bind">
<uni-forms-item label="賬號" name="account">
<input v-model.trim="ruleForm.account"
@blur="binddata('account', $event.detail.value)"
placeholder="請輸入您的登錄賬號" />
</uni-forms-item>
</uni-forms>
四、uni-forms自定義校驗規(guī)則
需要自定義校驗規(guī)則時,去掉uni-forms的:rules,同時onReady里加this.$refs.form.setRules(this.rules),其中validateFunction: this.checkEmail為自定義校驗方法
示例:
<template>
<uni-forms ref="form" :modelValue="ruleForm" validate-trigger="bind">
......
</uni-forms>
</template>
<script>
export default {
data() {
return {
// 校驗規(guī)則
rules: {
email: {
rules: [
{
validateFunction: this.checkEmail,
},
],
},
},
};
},
onReady() {
// 需要在onReady中設置規(guī)則
this.$refs.form.setRules(this.rules);
},
methods: {
/**
* 表單驗證郵箱
*/
checkEmail(rule, value, allData, callback) {
if (value !== "" && !verifyEmail(value)) {
return callback("郵箱不正確");
}
callback();
},
},
};
</script>五、uni-forms異步校驗
通常使用異步方法來校驗賬號是否重復等,步驟:
- 首先需要自定義校驗方法validateFunction: this.checkAccount
- 然后進行常規(guī)的規(guī)則校驗
- 再進行異步方法校驗賬號唯一性
需要使用Promise,校驗通過使用 return resolve()
校驗失敗使用 return reject(new Error('錯誤提示信息'))
示例(核心代碼部分):
export default {
data() {
return {
// 校驗規(guī)則
rules: {
account: {
rules: [
{
required: true,
errorMessage: '請輸入您的賬號',
},
{
validateFunction: this.checkAccount,
},
],
},
},
};
},
methods: {
// 表單驗證賬號
checkAccount(rule, value) {
return new Promise((resolve, reject) => {
// 先進行規(guī)則校驗
if (value === '' || !verifyAccount(value)) {
return reject(new Error('只能輸入4-30位英文、數(shù)字、下劃線'))
}
// 再進行異步校驗,checkUser為本系統(tǒng)api異步方法,結(jié)合你系統(tǒng)使用你自己的方法
apiCheckAccount({ account: value })
.then((data) => {
if (data.exist) {
return reject(new Error('賬號已存在'))
}
resolve()
})
.catch((err) => {
return reject(new Error(err.message))
})
})
},
},
六、完整示例源碼
<template>
<view class="register">
<view class="title">最實用表單校驗</view>
<uni-forms ref="form" :modelValue="ruleForm" validate-trigger="bind" label-width="40">
<uni-forms-item label="賬號" name="account">
<input v-model.trim="ruleForm.account" @blur="binddata('account', $event.detail.value)" placeholder="請輸入您的登錄賬號" />
</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: '', // 賬號
name: '', // 姓名
},
rules: {},
}
},
onReady() {
this.setRules()
// 需要在onReady中設置規(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('表單校驗失?。?, err)
})
},
// 設置校驗規(guī)則
setRules() {
this.rules = {
account: {
rules: [
{
required: true,
errorMessage: '請輸入您的賬號',
},
{
validateFunction: this.checkAccount,
},
],
},
name: {
rules: [
{
required: true,
errorMessage: '請輸入您的姓名',
},
{
validateFunction: this.checkName,
},
],
},
}
},
// 驗證賬號
checkAccount(rule, value) {
return new Promise((resolve, reject) => {
// 先進行規(guī)則校驗
if (value === '' || !verifyAccount(value)) {
return reject(new Error('只能輸入4-30位英文、數(shù)字、下劃線'))
}
// 再進行異步校驗,checkUser為本系統(tǒng)api異步方法,結(jié)合你系統(tǒng)使用你自己的方法
apiCheckAccount({ account: value })
.then((data) => {
if (data.exist) {
return reject(new Error('賬號已存在'))
}
resolve()
})
.catch((err) => {
return reject(new Error(err.message))
})
})
},
// 驗證姓名
checkName(rule, value, allData, callback) {
if (!verifyName(value)) {
return callback('只能輸入1-30位中英文和數(shù)字')
}
callback()
},
},
}
</script>
補充:記錄一個uni-forms表單每輸入一次就自動失去焦點的問題
局部代碼:
我之前是在key里面放了個input變量進去了,這確實也是個低級錯誤,但是此類問題的原因應該大同小異,就是v-for底層map循環(huán)的時候,key值發(fā)生了變化,導致dom更新,出現(xiàn)這個問題,去掉不確定性的key值綁定就好了

所以,用key要謹慎啊!一不小心找bug就是半天過去了
最后
到此這篇關于小程序表單校驗uni-forms正確使用方式以及避坑指南的文章就介紹到這了,更多相關小程序表單校驗uni-forms內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
js showModalDialog參數(shù)的使用詳解
本篇文章主要是對js中showModalDialog參數(shù)的使用進行了詳細的分析介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01

