Mini-program form verification uni-forms correct use method and pitfall guide

I. Introduction

The use of forms on applets should be a very common and necessary function. Because the system uses uni-app, uni-forms will be used at this time, but there are many problems encountered in the use process.
There are 3 requirements here:

  1. Instant verification (immediate verification value when the input box is out of focus)
  2. Custom validation rules are required
  3. Asynchronous verification is required

If these three requirements are met, most of the form verification can be realized. However, using the official case directly is not enough. After stepping on many pitfalls, the final solution is as follows.

2. Results display

The following displays all meet the above three requirements, and the following sample code can directly refer to the sixth point
insert image description here

3. Uni-forms instant verification

To realize instant verification, uni-forms need to be added validate-trigger="bind", and input is added at the same @blur="binddata('字段名', $event.detail.value)"
time Example:

 <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>

4. Uni-forms custom verification rules

When custom validation rules are required, 去掉uni-forms的:rules,同时onReady里加this.$refs.form.setRules(this.rules), where validateFunction: this.checkEmail is a custom validation method
Example:

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

<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      // 校验规则
      rules: {
      
      
        email: {
      
      
          rules: [
            {
      
      
              validateFunction: this.checkEmail,
            },
          ],
        },
      },
    };
  },
  onReady() {
      
      
    // 需要在onReady中设置规则
    this.$refs.form.setRules(this.rules);
  },
  methods: {
      
      
    /**
     * 表单验证邮箱
     */
    checkEmail(rule, value, allData, callback) {
      
      
      if (value !== "" && !verifyEmail(value)) {
      
      
        return callback("邮箱不正确");
      }
      callback();
    },
  },
};
</script>

Five, uni-forms asynchronous verification

Usually use an asynchronous method to check whether the account is duplicated, etc., steps:

  1. First, you need to customize the validation methodvalidateFunction: this.checkAccount
  2. Then perform regular rule checks
  3. Then use the asynchronous method to verify the uniqueness of the account.
    You need to use Promise. If the verification is passed, use it. If return resolve()
    the verification fails, use it.return reject(new Error('错误提示信息'))

Example (core code part):

export default {
    
    
  data() {
    
    
    return {
    
    
      // 校验规则
      rules: {
    
    
        account: {
    
    
          rules: [
            {
    
    
              required: true,
              errorMessage: '请输入您的账号',
            },
            {
    
    
              validateFunction: this.checkAccount,
            },
          ],
        },
      },
    };
  },
  methods: {
    
    
    // 表单验证账号
    checkAccount(rule, value) {
    
    
      return new Promise((resolve, reject) => {
    
    
        // 先进行规则校验
        if (value === '' || !verifyAccount(value)) {
    
    
          return reject(new Error('只能输入4-30位英文、数字、下划线'))
        }

        // 再进行异步校验,checkUser为本系统api异步方法,结合你系统使用你自己的方法
        apiCheckAccount({
    
     account: value })
          .then((data) => {
    
    
            if (data.exist) {
    
    
              return reject(new Error('账号已存在'))
            }
            resolve()
          })
          .catch((err) => {
    
    
            return reject(new Error(err.message))
          })
      })
    },
  },

6. Complete sample source code


<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 {
      
      
      // 表单数据
      ruleForm: {
      
      
        account: '', // 账号
        name: '', // 姓名
      },

      rules: {
      
      },
    }
  },
  onReady() {
      
      
    this.setRules()
    // 需要在onReady中设置规则
    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)
        })
    },

    // 设置校验规则
    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) => {
      
      
        // 先进行规则校验
        if (value === '' || !verifyAccount(value)) {
      
      
          return reject(new Error('只能输入4-30位英文、数字、下划线'))
        }

        // 再进行异步校验,checkUser为本系统api异步方法,结合你系统使用你自己的方法
        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位中英文和数字')
      }
      callback()
    },
  },
}
</script>

7. Finally, give a thumbs up

If it helps you, give it a thumbs up and leave :)

Guess you like

Origin blog.csdn.net/iamlujingtao/article/details/124757957