微信小程序之async-validator

文章目录

微信小程序之async-validator

概述

async-validator是一个基于 JavaScript 的表单验证库,支持异步验证规则和自定义验证规则

主流的 UI 组件库 Ant-designElement中的表单验证都是基于 async-validator

使用 async-validator 可以方便地构建表单验证逻辑,使得错误提示信息更加友好和灵活。

依赖库

复制代码
npm i async-validator

验证规则

type:识别类型

string: 必须是string.This is the default type.

number: 必须是number.

boolean: 必须是boolean.

method: 必须是function.

regexp: 必须是正则或者是在调用new RegExp 时不报错的字符串.

integer: 整数.

float: 浮点数.

array: 必须是数组,通过Array.isArray 判断.

object: 是对象且不为数组.

enum: 值必须出现在enmu 枚举值中.

date: 合法的日期,使用Date 判断

url: url.

hex: 16进制.

email: 邮箱地址.

required:是否必填

使用 required 属性判断是否必填。

pattern:正则

使用 pattern 属性支持正则验证。

range:范围

使用 min 和 max 属性定义值的范围。

length:长度

使用 len 属性定义值的长度,如果 len 与 max/min 同时使用,len 优先。

enum:枚举

复制代码
const descriptor = {
  role: { type: 'enum', enum: ['admin', 'user', 'guest'] },
};

使用

wxml:

复制代码
<input model:value="{{ userName }}" type="text" auto-focus placeholder="请输入姓名" />
<input model:value="{{ userAge }}" type="number" placeholder="请输入年龄" />
<input model:value="{{ userIdCard }}" type="idcard" placeholder="请输入身份证号" />
<input model:value="{{ userPhone }}" type="number" placeholder="请输入电话" />
<button bindtap="onCheck">验证</button>

js:

javascript 复制代码
import Schema from "async-validator"

Page({
  data: {
    userName: "",
    userAge: "",
    userIdCard: "",
    userPhone: "",
  },
  onValidator() {
    const nameReg = "^[a-zA-Z\\d\\u4e00-\\u9fa5]+$"
    const phoneReg = "^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$"
    // 定义规则
    const rules = {
      userName: [
        { required: true, message: "姓名不能为空" },
        { min: 2, max: 4, message: "姓名最少2个字,最多4个字" },
        { pattern: nameReg, message: "姓名不合法  " },
      ],
      userAge: [{ required: true, message: "年龄不能为空" }],
      userIdCard: [
        { required: true, message: "证件号不能为空" },
        { len: 18, message: "证件号必须是18位" },
      ],
      userPhone: [
        { required: true, message: "手机号不能为空" },
        { pattern: phoneReg, message: "手机号不合法" },
      ],
    }
    // 实例化
    const validator = new Schema(rules)
    // 验证
    validator.validate(this.data, (errors, fields) => {
      if (errors) {
        console.log("errors", errors)
        wx.showToast({
          title: errors[0].message,
        })
      } else {
        // 验证全部通过
        wx.showToast({
          title: "验证通过",
        })
      }
    })
  },
  onCheck() {
    this.onValidator()
  },
})
相关推荐
不如摸鱼去14 小时前
Wot UI 2.1.0 发布:ConfigProvider 全局配置能力升级
ui·小程序·uni-app
这是个栗子16 小时前
微信小程序开发(九)- uni-app微信小程序商城
微信小程序·小程序·uni-app·vue·vuex
TuCoder18 小时前
景区导览小程序功能选型指南:刚需配置、增值功能与技术避坑要点
小程序
小羊Yveesss21 小时前
2026年知识付费小程序多少钱一个?
小程序
一只皮卡皮卡丘21 小时前
微信小程序tab页苹果显示安卓不显示的问题
微信小程序·小程序
六月的可乐21 小时前
【干货】小程序虚拟瀑布流探索小结
前端·react.js·小程序
前端 贾公子2 天前
小程序蓝牙打印探索与实践(上)
小程序
拙慕JULY2 天前
小程序返回 base64 文件报错
开发语言·javascript·小程序
dh131222505252 天前
按月季度销售业绩核算小程序
小程序·销售小程序·绩效小程序·业绩统计小程序·业绩核算小程序
拙慕JULY2 天前
微信小程序自定义标题背景色
微信小程序·小程序