or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

error-handling.mdindex.mdmessages.mdrules.mdschema.mdvalidation-types.md
tile.json

tessl/npm-async-validator

Comprehensive asynchronous form validation library with flexible rule-based schemas and built-in validation types.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/async-validator@4.2.x

To install, run

npx @tessl/cli install tessl/npm-async-validator@4.2.0

index.mddocs/

Async Validator

Async Validator is a comprehensive asynchronous form validation library that enables developers to validate form data using flexible rule-based schemas with support for both synchronous and asynchronous validation functions. It provides a rich set of built-in validation types with customizable validation rules, error messages, and promise-based workflows.

Package Information

  • Package Name: async-validator
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install async-validator

Core Imports

import Schema from "async-validator";
import { RuleItem, Rules, ValidateCallback, ValidateError } from "async-validator";

For CommonJS:

const Schema = require("async-validator");

Basic Usage

import Schema from "async-validator";

// Define validation rules
const descriptor = {
  name: {
    type: "string",
    required: true,
    min: 2,
    max: 50
  },
  email: {
    type: "email",
    required: true
  },
  age: {
    type: "number",
    min: 18,
    max: 120
  }
};

// Create schema instance
const schema = new Schema(descriptor);

// Validate data
const userData = {
  name: "John Doe",
  email: "john@example.com",
  age: 25
};

// Using callback
schema.validate(userData, (errors, fields) => {
  if (errors) {
    console.log("Validation failed:", errors);
  } else {
    console.log("Validation passed");
  }
});

// Using promise
try {
  const result = await schema.validate(userData);
  console.log("Validation passed:", result);
} catch (error) {
  console.log("Validation failed:", error.errors);
}

Architecture

Async Validator is built around several key components:

  • Schema Class: Main validation orchestrator that manages rules and executes validation
  • Built-in Validators: Comprehensive set of type-specific validators (string, number, email, etc.)
  • Rule System: Flexible rule configuration with support for nested validation
  • Message System: Internationalization support with customizable error messages
  • Async Execution: Promise-based validation with support for asynchronous validators

Capabilities

Schema Management

Core schema creation and configuration for managing validation rules and executing validation operations.

class Schema {
  constructor(descriptor: Rules);
  define(rules: Rules): void;
  messages(messages?: ValidateMessages): InternalValidateMessages;
  validate(source: Values, option?: ValidateOption, callback?: ValidateCallback): Promise<Values>;
  validate(source: Values, callback: ValidateCallback): Promise<Values>;
  validate(source: Values): Promise<Values>;
  static register(type: string, validator: Function): void;
  static warning: (type: string, errors: SyncErrorType[]) => void;
  static messages: InternalValidateMessages;
  static validators: Record<string, ExecuteValidator>;
}

Schema Management

Rule Configuration

Flexible rule definition system supporting various validation types, custom validators, and nested object validation.

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>;
  defaultField?: Rule;
  transform?: (value: Value) => Value;
  message?: string | ((a?: string) => string);
  validator?: ValidatorFunction;
  asyncValidator?: AsyncValidatorFunction;
}

type Rule = RuleItem | RuleItem[];
type Rules = Record<string, Rule>;

Rule Configuration

Validation Types

Built-in validation support for all common data types including strings, numbers, arrays, objects, and specialized formats like email and URL.

type RuleType = 
  | "string" | "number" | "boolean" | "method" | "regexp" 
  | "integer" | "float" | "array" | "object" | "enum" 
  | "date" | "url" | "hex" | "email" | "pattern" | "any";

Validation Types

Error Handling

Comprehensive error reporting with field-specific errors, custom messages, and structured error objects.

interface ValidateError {
  message?: string;
  fieldValue?: Value;
  field?: string;
}

type ValidateFieldsError = Record<string, ValidateError[]>;

type ValidateCallback = (
  errors: ValidateError[] | null,
  fields: ValidateFieldsError | Values
) => void;

Error Handling

Message Customization

Internationalization support with customizable error messages for all validation types and scenarios.

interface ValidateMessages {
  default?: ValidateMessage;
  required?: ValidateMessage<[FullField]>;
  enum?: ValidateMessage<[FullField, EnumString]>;
  whitespace?: ValidateMessage<[FullField]>;
  date?: {
    format?: ValidateMessage;
    parse?: ValidateMessage;
    invalid?: ValidateMessage;
  };
  types?: Record<string, ValidateMessage>;
  string?: {
    len?: ValidateMessage<[FullField, Range]>;
    min?: ValidateMessage<[FullField, Range]>;
    max?: ValidateMessage<[FullField, Range]>;
    range?: ValidateMessage<[FullField, Range, Range]>;
  };
  // ... similar for number, array, pattern
}

Message Customization

Types

type Value = any;
type Values = Record<string, Value>;

interface ValidateOption {
  suppressWarning?: boolean;
  suppressValidatorError?: boolean;
  first?: boolean;
  firstFields?: boolean | string[];
  messages?: Partial<ValidateMessages>;
  keys?: string[];
  error?: (rule: InternalRuleItem, message: string) => ValidateError;
}

type SyncErrorType = Error | string;
type SyncValidateResult = boolean | SyncErrorType | SyncErrorType[];
type ValidateResult = void | Promise<void> | SyncValidateResult;

type ValidatorFunction = (
  rule: InternalRuleItem,
  value: Value,
  callback: (error?: string | Error) => void,
  source: Values,
  options: ValidateOption
) => SyncValidateResult | void;

type AsyncValidatorFunction = (
  rule: InternalRuleItem,
  value: Value,
  callback: (error?: string | Error) => void,
  source: Values,
  options: ValidateOption
) => void | Promise<void>;

type ValidateMessage<T extends any[] = unknown[]> =
  | string
  | ((...args: T) => string);

interface InternalValidateMessages extends ValidateMessages {
  clone: () => InternalValidateMessages;
}

interface InternalRuleItem extends Omit<RuleItem, 'validator'> {
  field?: string;
  fullField?: string;
  fullFields?: string[];
  validator?: RuleItem['validator'] | ExecuteValidator;
}

interface RuleValuePackage {
  rule: InternalRuleItem;
  value: Value;
  source: Values;
  field: string;
}

type ExecuteValidator = (
  rule: InternalRuleItem,
  value: Value,
  callback: (error?: string[]) => void,
  source: Values,
  options: ValidateOption
) => void;

type ExecuteRule = (
  rule: InternalRuleItem,
  value: Value,
  source: Values,
  errors: string[],
  options: ValidateOption,
  type?: string
) => void;