系列文章:

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

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

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

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|htmlentities(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. HTML实现代码雨源码及效果示例

    这篇文章主要介绍了HTML实现代码雨源码及效果示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  2. HTML5 WebSocket实现点对点聊天的示例代码

    这篇文章主要介绍了HTML5 WebSocket实现点对点聊天的示例代码的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  3. ios – 在Swift的UIView中找到UILabel

    我正在尝试在我的UIViewControllers的超级视图中找到我的UILabels.这是我的代码:这是在Objective-C中推荐的方式,但是在Swift中我只得到UIViews和CALayer.我肯定在提供给这个方法的视图中有UILabel.我错过了什么?我的UIViewController中的调用:解决方法使用函数式编程概念可以更轻松地实现这一目标.

  4. ios – 在Swift中将输入字段字符串转换为Int

    所以我非常擅长制作APP广告Swift,我试图在文本字段中做一些非常简单的输入,取值,然后将它们用作Int进行某些计算.但是’vardistance’有些东西不正确它是导致错误的最后一行代码.它说致命错误:无法解开Optional.None解决方法在你的例子中,距离是一个Int?否则称为可选的Int..toInt()返回Int?因为从String到Int的转换可能失败.请参阅以下示例:

  5. 如何在iOS中检测文本(字符串)语言?

    例如,给定以下字符串:我想检测每个声明的字符串中使用的语言.让我们假设已实现函数的签名是:如果没有检测到语言,则返回可选字符串.因此,适当的结果将是:有一个简单的方法来实现它吗?

  6. xamarin – 崩溃在AccountStore.Create().保存(e.Account,“);

    在Xamarin.Forms示例TodoAwsAuth中https://developer.xamarin.com/guides/xamarin-forms/web-services/authentication/oauth/成功登录后,在aOnAuthenticationCompleted事件中,应用程序在尝试保存到Xamarin.Auth时崩溃错误说不能对钥匙串说期待着寻求帮助.解决方法看看你

  7. ios – 将视频分享到Facebook

    我正在编写一个简单的测试应用程序,用于将视频从iOS上传到Facebook.由于FacebookSDK的所有文档都在Objective-C中,因此我发现很难在线找到有关如何使用Swift执行此操作的示例/教程.到目前为止我有这个在我的UI上放置一个共享按钮,但它看起来已禁用,从我读到的这是因为没有内容设置,但我看不出这是怎么可能的.我的getVideoURL()函数返回一个NSURL,它肯定包含视

  8. xcode – 错误“线程1:断点2.1”

    我正在研究RESTAPI管理器.这是一个错误,我无法解决它.我得到的错误在下面突出显示.当我打电话给这个班级获取资源时:我评论的线打印:Thread1:breakpoint2.1我需要修复错误的建议.任何建议都非常感谢解决方法您可能在不注意的情况下意外设置了断点.单击并拖动代表断路器外部断点的蓝色刻度线以将其擦除.

  9. ios – 更改导航栏标题swift中的字符间距

    类型的值有人可以帮我这个或建议一种不同的方式来改变swift中导航栏标题中的字符间距吗?解决方法您无法直接设置属性字符串.你可以通过替换titleView来做一个技巧

  10. ios – 如何从变量访问属性或方法?

    是否可以使用变量作为Swift中方法或属性的名称来访问方法或属性?在PHP中,您可以使用$object->{$variable}.例如编辑:这是我正在使用的实际代码:解决方法你可以做到,但不能使用“纯粹的”Swift.Swift的重点是防止这种危险的动态属性访问.你必须使用Cocoa的Key-ValueCoding功能:非常方便,它完全穿过你要穿过的字符串到属性名称的桥,但要注意:这里是龙.

随机推荐

  1. js中‘!.’是什么意思

  2. Vue如何指定不编译的文件夹和favicon.ico

    这篇文章主要介绍了Vue如何指定不编译的文件夹和favicon.ico,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  3. 基于JavaScript编写一个图片转PDF转换器

    本文为大家介绍了一个简单的 JavaScript 项目,可以将图片转换为 PDF 文件。你可以从本地选择任何一张图片,只需点击一下即可将其转换为 PDF 文件,感兴趣的可以动手尝试一下

  4. jquery点赞功能实现代码 点个赞吧!

    点赞功能很多地方都会出现,如何实现爱心点赞功能,这篇文章主要为大家详细介绍了jquery点赞功能实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  5. AngularJs上传前预览图片的实例代码

    使用AngularJs进行开发,在项目中,经常会遇到上传图片后,需在一旁预览图片内容,怎么实现这样的功能呢?今天小编给大家分享AugularJs上传前预览图片的实现代码,需要的朋友参考下吧

  6. JavaScript面向对象编程入门教程

    这篇文章主要介绍了JavaScript面向对象编程的相关概念,例如类、对象、属性、方法等面向对象的术语,并以实例讲解各种术语的使用,非常好的一篇面向对象入门教程,其它语言也可以参考哦

  7. jQuery中的通配符选择器使用总结

    通配符在控制input标签时相当好用,这里简单进行了jQuery中的通配符选择器使用总结,需要的朋友可以参考下

  8. javascript 动态调整图片尺寸实现代码

    在自己的网站上更新文章时一个比较常见的问题是:文章插图太宽,使整个网页都变形了。如果对每个插图都先进行缩放再插入的话,太麻烦了。

  9. jquery ajaxfileupload异步上传插件

    这篇文章主要为大家详细介绍了jquery ajaxfileupload异步上传插件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. React学习之受控组件与数据共享实例分析

    这篇文章主要介绍了React学习之受控组件与数据共享,结合实例形式分析了React受控组件与组件间数据共享相关原理与使用技巧,需要的朋友可以参考下

返回
顶部