系列文章:

1、async-validator 源码学习(一):文档翻译

2、async-validator 源码学习笔记(二):目录结构

rule 主要实现的是校验规则,文件结构为下图:

一、rule 目录文件介绍

其中 index.d.ts 文件:

declare const _default: {
required: import("..").ExecuteRule;
whitespace: import("..").ExecuteRule;
type: import("..").ExecuteRule;
range: import("..").ExecuteRule;
enum: import("..").ExecuteRule;
pattern: import("..").ExecuteRule;
};
export default _default;

是 rule 目录的统一出口管理,主要是给 errors 数组添加对应的 error 。

required.d.ts 文件:

import { ExecuteRule } from '../interface';
declare const required: ExecuteRule;
export default required;

主要作用是校验必填字段的规则。

其中 ExecuteRule 是来自于 interface.d.ts 文件中的

// 摘自其中的一部分
export declare type ExecuteRule = (
rule: InternalRuleItem,
value: Value,
source: Values,
errors: string[],
options: ValidateOption,
type?: string
) => void;
/**
* Performs validation for any type.
*
* @param rule The validation rule.
* @param value The value of the field on the source object.
* @param callback The callback function.
* @param source The source object being validated.
* @param options The validation options.
* @param options.messages The validation messages.
*/

ExecuteRule 是统一定义的函数类型别名,统一了函数传递参数和返回值的类型。等价于:

declare const required(rule, value, source, errors, options, type) 

方法内的参数及其意义如下:

  • @param rule 校验的规则
  • @param value 需要校验字段的当前值
  • @param source 需要校验的字段
  • @param errors 本次校验将要去添加的 errors 数组
  • @param options 校验选项
  • @param options.message 校验的 messages

type.d.ts

import { ExecuteRule } from '../interface';
declare const type: ExecuteRule;
export default type;

校验值的类型,可能的类型有:integer、float、array、regexp、object、method、email、number、data、url、hex

range.d.ts

import { ExecuteRule } from '../interface';
declare const range: ExecuteRule;
export default range;

校验是否满足最大最小值合理区间的规则

whitespace.d.ts

import { ExecuteRule } from '../interface';
/**
* Rule for validating whitespace.
*
* @param rule The validation rule.
* @param value The value of the field on the source object.
* @param source The source object being validated.
* @param errors An array of errors that this rule may add
* validation errors to.
* @param options The validation options.
* @param options.messages The validation messages.
*/
declare const whitespace: ExecuteRule;
export default whitespace;

校验空白字符的规则

enum.d.ts

import { ExecuteRule } from '../interface';
declare const enumerable: ExecuteRule;
export default enumerable;

校验值是否存在枚举值列表中的规则

pattern.d.ts

import { ExecuteRule } from '../interface';
declare const pattern: ExecuteRule;
export default pattern;

校验正则表达式的规则

二、rule 应用

interface.d.ts 中定义 rule 单元格式

export interface RuleItem {
type?: RuleType; //类型
required?: boolean; //是否为空
pattern?: RegExp | string; //正则
min?: number; // 最小值或长度
max?: number; //最大值或长度
len?: number; // 长度
enum?: Array<string | number | boolean | null | undefined>; //校验值是否存在枚举值列表中的规则
whitespace?: boolean; //是否空白
fields?: Record<string, Rule>;//深度监听属性和规则
options?: ValidateOption;//选项
defaultField?: Rule; //校验属性内部值
transform?: (value: Value) => Value; //校验前转换
message?: string | ((a?: string) => string);//信息提示
//异步校验
asyncValidator?: (rule: InternalRuleItem, value: Value, callback: (error?: string | Error) => void, source: Values, options: ValidateOption) => void | Promise<void>;
//同步校验
validator?: (rule: InternalRuleItem, value: Value, callback: (error?: string | Error) => void, source: Values, options: ValidateOption) => SyncValidateResult | void;
}
// Rule 可以是一个对象,也可以是该对象的数组
export declare type Rule = RuleItem | RuleItem[];

rule 是本字段对应的校验规则:

{
field: "name",
fullField: "name",
message: "姓名为必填项",
required: false,
type: "string",
validator: ƒ required$1(rule, value, callback, source, options)
}

value 是本字段的值:如小明

source 是要校验的整个 source 对象:

{
name: '小明',
info: {
age: 17,
}
}

errors 是本次校验将要去添加的 errors 数组,假设之前没有 error,则 errors 为[],如果之前已经存在了一些 error,则格式如下所示:

[
{
message: '年龄超出范围',
field: 'info.age',
}
]

options 是该字段校验时的选项,当 message 属性为默认值时,格式如下:

{
firstFields: true,
messages: {
array: {len: "%s must be exactly %s in length", min: "%s cannot be less than %s in length", max: "%s cannot be greater than %s in length", range: "%s must be between %s and %s in length"},
clone: ƒ clone(),
date: {format: "%s date %s is invalid for format %s", parse: "%s date could not be parsed, %s is invalid ", invalid: "%s date %s is invalid"},
default: "Validation error on field %s",
enum: "%s must be one of %s",
number: {len: "%s must equal %s", min: "%s cannot be less than %s", max: "%s cannot be greater than %s", range: "%s must be between %s and %s"},
pattern: {mismatch: "%s value %s does not match pattern %s"},
required: "%s is required",
string: {len: "%s must be exactly %s characters", min: "%s must be at least %s characters", max: "%s cannot be longer than %s characters", range: "%s must be between %s and %s characters"},
types: {string: "%s is not a %s", method: "%s is not a %s (function)", array: "%s is not an %s", object: "%s is not an %s", number: "%s is not a %s", …},
whitespace: "%s cannot be empty",
}
}

三、项目开发应用

实际项目开发中验证规则 rule 的写法:

const rules = {
// 深度校验1
address: {
type: 'object',
required: true,
fields: {
//深度校验street属性
street: { type: 'string', required: true },
city: { type: 'string', required: true },
zip: {
type: 'string',
required: true,
len: 8,
message: 'invalid zip',
},
},
},
//校验 2 数组形式
username: [
{
type: 'string',
required: true,
whitespace: true,
transform(value) {
return value.trim()
},
message: '用户名不能为空格',
// 异步校验
asyncValidator: (rule, value) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (value != '') {
resolve()
} else {
reject('error')
}
}, 2000)
})
},
},
{
type: 'string',
min: 3,
max: 20,
message: '长度 3- 20 位',
},
],
}

async-validator 源码学习笔记(三):rule的更多相关文章

  1. jquery源码学习笔记三:jQuery工厂剖析

    jquery源码学习笔记二:jQuery工厂 jquery源码学习笔记一:总体结构 上两篇说过,query的核心是一个jQuery工厂.其代码如下 function( window, noGlobal ...

  2. yii2源码学习笔记(三)

    组件(component),是Yii框架的基类,实现了属性.事件.行为三类功能,如果需要事件和行为的功能,需要继承该类. yii\base\Component代码详解 <?php /** * @ ...

  3. async-validator 源码学习笔记(四):validator

    系列文章: 1.async-validator 源码学习(一):文档翻译 2.async-validator 源码学习笔记(二):目录结构 3.async-validator 源码学习笔记(三):ru ...

  4. async-validator 源码学习笔记(五):Schema

    系列文章: 1.async-validator 源码学习(一):文档翻译 2.async-validator 源码学习笔记(二):目录结构 3.async-validator 源码学习笔记(三):ru ...

  5. async-validator 源码学习笔记(六):validate 方法

    系列文章: 1.async-validator 源码学习(一):文档翻译 2.async-validator 源码学习笔记(二):目录结构 3.async-validator 源码学习笔记(三):ru ...

  6. Spring源码学习笔记12——总结篇,IOC,Bean的生命周期,三大扩展点

    Spring源码学习笔记12--总结篇,IOC,Bean的生命周期,三大扩展点 参考了Spring 官网文档 https://docs.spring.io/spring-framework/docs/ ...

  7. Underscore.js 源码学习笔记(下)

    上接 Underscore.js 源码学习笔记(上) === 756 行开始 函数部分. var executeBound = function(sourceFunc, boundFunc, cont ...

  8. Hadoop源码学习笔记(5) ——回顾DataNode和NameNode的类结构

    Hadoop源码学习笔记(5) ——回顾DataNode和NameNode的类结构 之前我们简要的看过了DataNode的main函数以及整个类的大至,现在结合前面我们研究的线程和RPC,则可以进一步 ...

  9. Hadoop源码学习笔记(1) ——第二季开始——找到Main函数及读一读Configure类

    Hadoop源码学习笔记(1) ——找到Main函数及读一读Configure类 前面在第一季中,我们简单地研究了下Hadoop是什么,怎么用.在这开源的大牛作品的诱惑下,接下来我们要研究一下它是如何 ...

随机推荐

  1. MLlib学习——基本统计

    给定一个数据集,数据分析师一般会先观察一下数据集的基本情况,称之为汇总统计或者概要性统计.一般的概要性统计用于概括一系列观测值,包括位置或集中趋势(比如算术平均值.中位数.众数和四分位均值),展型(比 ...

  2. linux13

    ansible-playbook实现MySQL的二进制部署 Ansible playbook实现apache批量部署,并对不同主机提供以各自IP地址为内容的index.html http的报文结构和状 ...

  3. JavaWeb中jsp路径斜杆(/)跟没斜杆的路径映射问题

    在JavaWeb开发中,只要是写URL地址,那么建议最好以"/"开头,也就是使用绝对路径的方式,那么这个"/"到底代表什么呢?可以用如下的方式来记忆" ...

  4. InfluxDB 2.x Open Source Time Series Database

    1. 说明 目前,大家普遍还在采用 InfluxDB 1.x 的版本,官方2.x的版本已经发布一段时间了, 其主推flux语言且自带前端炫酷图表. 2. 官方网站 https://www.influx ...

  5. HTTP协议和HTTPS协议的那些事

    文章目录 HTTPS VS HTTP HTTPS=HTTP+加密+证书+完整性保护 加密 对称加密 非对称加密 混合加密 证书 完整性保护 HTTPS并不能取代HTTP SSL是把双刃剑 HTTPS的 ...

  6. Spring Security即将弃用WebSecurityConfigurerAdapter配置类

    用过WebSecurityConfigurerAdapter的都知道对Spring Security十分重要,总管Spring Security的配置体系.但是马上这个类要废了,你没有看错,这个类将在 ...

  7. Zabbix 6.0:原生高可用(HA)方案部署

    Blog:博客园 个人 本部署文档适用于CentOS 8.X/RHEL 8.X/Anolis OS 8.X/AlmaLinux 8.X/Rockey Linux 8.X. 原生的HA方案终于来了 相比 ...

  8. 用实例带你深入理解Java内存模型

    摘要:本文的目的来理解 J V M 与我们的内存两者之间是如何协调工作的. 本文分享自华为云社区<一文带你图解Java内存模型>,作者: 龙哥手记 . 我们今天要特别重点讲的,也就是我们本 ...

  9. IE内核 播放 RTMP 视频

    VLC IE ActiveX 方式播放 需IE内核支持(IE或者双核浏览器). VLC 下载地址https://www.videolan.org/vlc/ 页面视频窗口 <div id=&quo ...

  10. [Matlab]求解线性方程组

    转自:http://silencethinking.blog.163.com/blog/static/911490562008928105813169/ AX=B或XA=B在MATLAB中,求解线性方 ...