微信小程序之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()
  },
})
相关推荐
浩星2 小时前
react+taro打包到不同小程序
react.js·小程序·taro
Jun28115 小时前
微信小程序初探之数据绑定
微信小程序
顾辰逸you15 小时前
uniapp--咸虾米壁纸(三)
前端·微信小程序
大包子17 小时前
小程序分享(下载)海报随记
微信小程序
996幸存者18 小时前
下拉、上拉选择器 支持搜索、删除、自定义选择内容、任意对象字段映射
微信小程序·uni-app
diygwcom21 小时前
AI实现超级客户端打印 支持APP 网页 小程序 调用本地客户端打印
小程序
zkmall1 天前
ZKmall模块商城的推荐数据体系:从多维度采集到高效存储的实践
小程序·架构·开源·代码规范
源码哥_博纳软云1 天前
JAVA国际版多商户运营版商城系统源码多商户社交电商系统源码支持Android+IOS+H5
android·java·ios·微信·微信小程序·小程序·uni-app
顾辰逸you1 天前
uniapp--咸虾米壁纸项目(二)
前端·微信小程序
CRMEB定制开发1 天前
CRMEB私域电商系统后台开发实战:小程序配置全流程解析
小程序·开源软件·小程序商城·商城源码·微信商城·crmeb