赞
踩
async-validator 是一个基于 JavaScript 的表单验证库,支持异步验证规则和自定义验证规则
主流的 UI 组件库 Ant-design 和 Element 中的表单验证都是基于 async-validator
使用 async-validator 可以方便地 构建表单中逻辑,使得错误提示信息更加友好和灵活。
- 安装并在项目中导入 async-validator
- 创建验证规则
- 创建表单验证实例,将验证规则传递给构造函数,产生实例
- 调用实例方法 validate 对数据进行验证
第一个参数:需要验证地数据
第二个参数:回调函数,回调函数有两个参数 errors,fields
errors:如果验证成功,返回 null 验证错误 返回数据
fields:需要验证地字段,属性值错误数据
// 从 async-validator 中引入构造函数 import Schema from 'async-validator'; const app = getApp() Page({ data: { orderAddress: {}, orderInfo: {}, // 订单详情 show: false, currentDate: new Date().getTime(), minDate: new Date().getTime(), deliveryDate: "", buyName: '', buyPhone: '', blessing: '', }, // 处理提交订单 async onSubmit() { // 需要从 data 中结构数据 // 需要根据接口要求组织请求参数 const { deliveryDate, buyName, buyPhone, blessing, orderAddress, orderInfo } = this.data // 需要根据接口要求组织请求参数 const params = { buyName, buyPhone, deliveryDate, cartList: orderInfo.cartVoList, remarks: blessing, userAddressId: orderAddress.id } const { valid } = await this.validatorAddress(params) console.log(valid)// true/false }, validatorAddress(params) { // 验证订购人,是否包含大小写字母、数字和中文字符 const nameRegExp = '^[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 = { userAddressId: { required: true, message: '请选择地址' }, buyName: [ { required: true, message: '请输入姓名' }, { pattern: nameRegExp, message: '不合法' } ], buyPhone: [ { required: true, message: '请输入手机号' }, { pattern: phoneReg, message: '手机号不合法' } ], deliveryDate: { required: true, message: '请选择日期' }, } // 传入验证规则进行实例化 const validator = new Schema(rules) // 调用示例方法对请求参数进行验证 // 注意:我们希望将验证通过 Promise 的形式返回给函数的调用者 return new Promise((resolve) => { validator.validate(params, (errors) => { if (errors) { // 如果验证失败,需要给用户进行提示 wx.toast({ title: errors[0].message }) // 如果属性值是 false,说明验证失败 resolve({ valid: false }) } else { // 如果属性值是 true,说明验证成功 resolve({ valid: true }) } }) }) }, })
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。