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.
npm install async-validatorimport Schema from "async-validator";
import { RuleItem, Rules, ValidateCallback, ValidateError } from "async-validator";For CommonJS:
const Schema = require("async-validator");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);
}Async Validator is built around several key components:
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>;
}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>;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";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;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
}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;