async-validator

repository·master·Indexed 27 days ago

https://github.com/yiminghe/async-validator

An asynchronous form validation library for defining complex validation schemas. It supports both synchronous rules and asynchronous validators returning Promises, allowing developers to validate objects using built-in types (string, number, email, url, etc.), custom validation functions, and deep rules for nested objects and arrays. Version 4.2.5 includes features for value transformation, custom error message configuration, and flexible execution options like stopping at the first error.

Tokens
3.4K
Snippets
9
Records
24
Agent score
94%

What's inside async-validator

  1. Validate nested object and array properties (Deep Rules)

    master

    To validate deep structures, use the fields property within an object or array type rule.

    • For Objects: Assign a fields object containing rules for the nested properties.
    • For Arrays: Assign a fields object where keys are indices (e.g., '0', '1') to validate specific elements.
    • defaultField: For array or object types, you can use defaultField to apply the same rule to all elements/values in the container. This is expanded to fields internally.
    const descriptor = {
      address: {
        type: 'object',
        required: true,
        fields: {
          street: { type: 'string', required: true },
          city: { type: 'string', required: true },
        },
      },
      urls: {
        type: 'array',
        required: true,
        defaultField: { type: 'url' },
      },
    };
  2. Transform values before validation

    master

    Use the transform function in a rule to sanitize or coerce data before the validation rules are applied. The transformed value is what is passed to subsequent validators and returned in the validation result.

    Note: The transform function should return the transformed value.

    const descriptor = {
      name: {
        type: 'string',
        required: true,
        pattern: /^[a-z]+$/,
        transform(value) {
          return value.trim();
        },
      },
    };
    
    const validator = new Schema(descriptor);
    const source = { name: ' user  ' };
    
    // Validation passes because 'user' is trimmed before pattern check
    validator.validate(source).then((data) => {
      console.log(data.name); // 'user'
    });
  3. Basic usage of async-validator

    master

    To use async-validator, define a descriptor object containing validation rules, instantiate a Schema with that descriptor, and call the validate method on the object you wish to validate. You can use either a callback function or a Promise-based approach.

    import Schema from 'async-validator';
    const descriptor = {
      name: {
        type: 'string',
        required: true,
        validator: (rule, value) => value === 'muji',
      },
      age: {
        type: 'number',
        asyncValidator: (rule, value) => {
          return new Promise((resolve, reject) => {
            if (value < 18) {
              reject('too young');  // reject with error message
            } else {
              resolve();
            }
          });
        },
      },
    };
    const validator = new Schema(descriptor);
    
    // Callback usage
    validator.validate({ name: 'muji' }, (errors, fields) => {
      if (errors) {
        // validation failed, errors is an array of all errors
        // fields is an object keyed by field name with an array of
        // errors per field
        return handleErrors(errors, fields);
      }
      // validation passed
    });
    
    // PROMISE USAGE
    validator.validate({ name: 'muji', age: 16 }).then(() => {
      // validation passed or without error message
    }).catch(({ errors, fields }) => {
      return handleErrors(errors, fields);
    });
  4. Customize validation error messages

    master

    You can customize error messages at different levels:

    1. Per Rule: Assign a message property directly to a rule. { name: { type: 'string', required: true, message: 'Name is required' } }
    2. Global/Schema Level: Use validator.messages(customMessages) to deep merge custom messages with default ones. This is useful for i18n.
    3. Inside Custom Validators: Access options.messages within a validator function to retrieve custom messages defined in the schema.
    import Schema from 'async-validator';
    
    // Global message override
    const cn = { required: '%s 必填' };
    const descriptor = { name: { type: 'string', required: true } };
    const validator = new Schema(descriptor);
    validator.messages(cn);
  5. Configure validation options

    master

    When calling validate, you can pass an options object to control execution flow:

    • suppressWarning (Boolean): Whether to suppress internal warnings about invalid values.
    • first (Boolean): If true, the callback is invoked as soon as the first validation rule generates an error. No further rules are processed. Useful for expensive asynchronous checks (e.g., database queries).
    • firstFields (Boolean|String[]): If true, the callback is invoked when the first rule of any field fails. If an array of strings is provided, it triggers when the first rule of the specified fields fails. No more rules for those specific fields are processed.
  6. Avoid global warnings in async-validator

    master

    To suppress global warnings emitted by async-validator, you can either override the Schema.warning method with an empty function or set the ASYNC_VALIDATOR_NO_WARNING environment variable on globalThis to 1.

    import Schema from 'async-validator';
    Schema.warning = function(){};
  7. Validate data with Schema.validate()

    master

    The validate method is used to validate a source object against a schema descriptor. It can be used with a callback or as a Promise.

    Arguments:

    • source (required): The object to validate.
    • options (optional): An object describing processing options.
    • callback (optional): A function invoked when validation completes.

    Return Values:

    • Promise:
      • Resolves (.then()) if validation passes.
      • Rejects (.catch({ errors, fields })) if validation fails. errors is an array of all errors; fields is an object keyed by field name containing an array of errors per field.
    • Callback: Invoked with (errors, fields).
  8. Define custom validation functions

    master

    You can define custom validation logic using validator or asyncValidator within your schema descriptor.

    validator (Synchronous/Simple):

    • Can return false, an Error, an Error array, or simply call the callback.
    • Signature: function(rule, value, callback, source, options)

    asyncValidator (Asynchronous):

    • Use this for operations like AJAX calls or database lookups.
    • You can either use the callback pattern or return a Promise.
  9. Use built-in rule types

    master

    The type property in a rule defines the validation logic. Supported types include:

    • string: Default type.
    • number, integer, float: Numeric validations.
    • boolean: Must be a boolean.
    • method: Must be a function.
    • regexp: Must be a RegExp instance or a valid regex string.
    • array: Must be an array.
    • object: Must be an object (not an array).
    • enum: Value must exist in the provided enum array.
    • date: Must be a valid Date.
    • url, hex, email: Format-specific validations.
    • any: Accepts any type.
  10. Apply common rule properties: required, pattern, range, length, and whitespace

    master

    Standard rule properties for common validation tasks:

    • required (Boolean): The field must exist on the source object.
    • pattern (RegExp|String): The value must match this regular expression.
    • min / max: Defines a range. For string/array, it checks length. For number, it checks the value.
    • len (Number): Specifies an exact length for string/array, or an exact value for number. len takes precedence over min/max.
    • whitespace (Boolean): If true (and type is string), a string consisting only of whitespace will be treated as an error.