web123456

async-validator source code study notes (3): rule

Series of articles:

1、async-validator source code study (I): documentation translation

2、async-validator source code study notes (II): directory structure

The main implementation of rule is the checksum rule, the file structure is the following figure:

I. Introduction to Rule Catalog Files

Among the documents:

  1. declare const _default: {
  2. required: import("..").ExecuteRule;
  3. whitespace: import("..").ExecuteRule;
  4. type: import("..").ExecuteRule;
  5. range: import("..").ExecuteRule;
  6. enum: import("..").ExecuteRule;
  7. pattern: import("..").ExecuteRule;
  8. };
  9. export default _default;

is a unified export manager for rule directories, mainly for errorsThe array addsThe corresponding error.

Documentation:

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

The main function is to check the rules for required fields.

where ExecuteRule is from the file

  1. // Excerpts from some of them
  2. export declare type ExecuteRule = (
  3. rule: InternalRuleItem,
  4. value: Value,
  5. source: Values,
  6. errors: string[],
  7. options: ValidateOption,
  8. type?: string
  9. ) => void;
  10. /**
  11. * Performs validation for any type.
  12. *
  13. * @param rule The validation rule.
  14. * @param value The value of the field on the source object.
  15. * @param callback The callback function.
  16. * @param source The source object being validated.
  17. * @param options The validation options.
  18. * @param The validation messages.
  19. */

ExecuteRule is a uniformly definedfunction class (math.)Type aliases that unify the types of parameters and return values passed to a function. Equivalent:

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

The parameters within the method and their significance are listed below:

  • @param rule The rule to verify
  • @param value The current value of the field to be checked.
  • @param source Fields to be verified
  • @param errors An array of errors to add to this check.
  • @param options Checksum options
  • @param verified messages

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

The type of the checksum value, the possible types are: integer, float,array、regexp、object、method、email、number、data、url、hex

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

Check that the rules for the maximum and minimum reasonable intervals are satisfied

  1. import { ExecuteRule } from '../interface';
  2. /**
  3. * Rule for validating whitespace.
  4. *
  5. * @param rule The validation rule.
  6. * @param value The value of the field on the source object.
  7. * @param source The source object being validated.
  8. * @param errors An array of errors that this rule may add
  9. * validation errors to.
  10. * @param options The validation options.
  11. * @param The validation messages.
  12. */
  13. declare const whitespace: ExecuteRule;
  14. export default whitespace;

Rules for checking whitespace characters

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

Whether the checksum value existsenumerated valueRules in the list

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

Rules for calibrating regular expressions

II. RULE APPLICATIONS

Define the rule unit format in

  1. export interface RuleItem {
  2. type?: RuleType; //typology
  3. required?: boolean; //Whether or not it is empty
  4. pattern?: RegExp | string; //regular (figure in geometry)
  5. min?: number; // Minimum value or length
  6. max?: number; //Maximum value or length
  7. len?: number; // lengths
  8. enum?: Array<string | number | boolean | null | undefined>; //Rules for checking whether a value exists in a list of enumerated values
  9. whitespace?: boolean; //Blank or not
  10. fields?: Record<string, Rule>;//Deep Listening Properties and Rules
  11. options?: ValidateOption;//options (as in computer software settings)
  12. defaultField?: Rule; //Validating the internal value of an attribute
  13. transform?: (value: Value) => Value; //pre-check conversion
  14. message?: string | ((a?: string) => string);//Information Alerts
  15. //asynchronous calibration
  16. asyncValidator?: (rule: InternalRuleItem, value: Value, callback: (error?: string | Error) => void, source: Values, options: ValidateOption) => void | Promise<void>;
  17. //synchronized verification
  18. validator?: (rule: InternalRuleItem, value: Value, callback: (error?: string | Error) => void, source: Values, options: ValidateOption) => SyncValidateResult | void;
  19. }
  20. // A Rule can be an object or an array of such objects.
  21. export declare type Rule = RuleItem | RuleItem[];

rule is the checksum rule corresponding to this field:

  1. {
  2. field: "name",
  3. fullField: "name",
  4. message: "Name is required.",
  5. required: false,
  6. type: "string",
  7. validator: ƒ required$1(rule, value, callback, source, options)
  8. }

value is the value of this field: e.g. Xiaoming

source is the entire source object to be verified:

  1. {
  2. name: 'Little Ming',
  3. info: {
  4. age: 17,
  5. }
  6. }

errors is the array of errors to be added to this check, assuming there are no previous errors, then errors is [], if there are already some previous errors, then the format is as follows:

  1. [
  2. {
  3. message: 'Age out of range',
  4. field: ''
  5. }
  6. ]

options are the options for this field when it is validated, in the following format when the message attribute is the default value:

  1. {
  2. firstFields: true,
  3. messages: {
  4. 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"},
  5. clone: ƒ clone(),
  6. 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"},
  7. default: "Validation error on field %s",
  8. enum: "%s must be one of %s",
  9. 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"},
  10. pattern: {mismatch: "%s value %s does not match pattern %s"},
  11. required: "%s is required",
  12. 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"},
  13. 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", …},
  14. whitespace: "%s cannot be empty",
  15. }
  16. }

III. Project development applications

Ways to write validation rule rule in real project development:

  1. const rules = {
  2. // deep calibration1
  3. address: {
  4. type: 'object',
  5. required: true,
  6. fields: {
  7. //Deep-checking the street attribute
  8. street: { type: 'string', required: true },
  9. city: { type: 'string', required: true },
  10. zip: {
  11. type: 'string',
  12. required: true,
  13. len: 8,
  14. message: 'invalid zip',
  15. },
  16. },
  17. },
  18. //calibration2 array form
  19. username: [
  20. {
  21. type: 'string',
  22. required: true,
  23. whitespace: true,
  24. transform(value) {
  25. return value.trim()
  26. },
  27. message: 'Username cannot be a space',
  28. // asynchronous calibration
  29. asyncValidator: (rule, value) => {
  30. return new Promise((resolve, reject) => {
  31. setTimeout(() => {
  32. if (value != '') {
  33. resolve()
  34. } else {
  35. reject('error')
  36. }
  37. }, 2000)
  38. })
  39. },
  40. },
  41. {
  42. type: 'string',
  43. min: 3,
  44. max: 20,
  45. message: 'Length 3-20 bits',
  46. },
  47. ],
  48. }