微信小程序之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()
  },
})
相关推荐
黄华SJ520it2 小时前
新零售排队免单系统开发全流程介绍
小程序·零售·系统开发
衍生星球1 天前
SpringBoot3 + Vue3 + 微信小程序如何学习,以及学哪些技术,组件
sql·微信小程序·uni-app·vue·springboot
weixin_451431561 天前
落地到一个真实项目里——一个 AI驱动的冰箱食材管理小程序
人工智能·ai·小程序
hnxaoli2 天前
统信小程序(十六)xls转xlsx
开发语言·python·小程序
卓怡学长2 天前
w272基于springboot便民医疗服务小程序
java·spring boot·spring·小程序·intellij-idea
新华财经频道2 天前
2026微信小程序搭建平台实测测评,优缺点解析
微信小程序·小程序
kidding7232 天前
旋转大转盘小程序
前端·css·微信小程序·小程序·前端框架
码农客栈3 天前
小程序学习(二十九)之项目打包
小程序
凡科建站3 天前
2026年艺术类教育小程序开发平台有哪些?艺术类教育小程序开发平台推荐
小程序
LT10157974443 天前
2026年在线兼容性测试工具推荐|零部署网页 / APP / 小程序实测对比
测试工具·小程序