Core schema creation and configuration for managing validation rules and executing validation operations.
Creates a new schema instance with validation rules.
/**
* Creates a validation schema with the provided descriptor
* @param descriptor - Object declaring validation rules for this schema
*/
constructor(descriptor: Rules);Usage Example:
import Schema from "async-validator";
const rules = {
name: { type: "string", required: true },
age: { type: "number", min: 0, max: 120 }
};
const schema = new Schema(rules);Define or redefine validation rules for the schema.
/**
* Define validation rules for the schema
* @param rules - Object mapping field names to validation rules
* @throws Error if rules is not provided or not an object
*/
define(rules: Rules): void;Usage Example:
const schema = new Schema({});
// Define rules after creation
schema.define({
username: [
{ type: "string", required: true, min: 3 },
{ pattern: /^[a-zA-Z0-9_]+$/, message: "Username can only contain letters, numbers, and underscores" }
],
password: { type: "string", required: true, min: 8 }
});Get or set custom validation messages for internationalization.
/**
* Get current messages or set custom validation messages
* @param messages - Optional custom messages to merge with defaults
* @returns Current validation messages object
*/
messages(messages?: ValidateMessages): InternalValidateMessages;Usage Example:
// Get current messages
const currentMessages = schema.messages();
// Set custom messages
schema.messages({
required: "%s is a required field",
types: {
string: "%s must be a text value",
number: "%s must be a numeric value"
},
string: {
min: "%s must be at least %s characters long"
}
});Main validation method with multiple signatures for different usage patterns.
/**
* Validate data against the schema rules
* @param source - Object containing data to validate
* @param option - Optional validation configuration
* @param callback - Optional callback function for results
* @returns Promise that resolves with validated data or rejects with errors
*/
validate(
source: Values,
option?: ValidateOption,
callback?: ValidateCallback
): Promise<Values>;
/**
* Validate data with callback
* @param source - Object containing data to validate
* @param callback - Callback function for results
* @returns Promise that resolves with validated data or rejects with errors
*/
validate(source: Values, callback: ValidateCallback): Promise<Values>;
/**
* Validate data and return promise
* @param source - Object containing data to validate
* @returns Promise that resolves with validated data or rejects with errors
*/
validate(source: Values): Promise<Values>;Usage Examples:
// Promise-based validation
try {
const validatedData = await schema.validate({
name: "John Doe",
age: 25
});
console.log("Validation passed:", validatedData);
} catch (error) {
console.log("Validation errors:", error.errors);
console.log("Field errors:", error.fields);
}
// Callback-based validation
schema.validate(
{ name: "John", age: 25 },
{ first: true }, // Stop on first error
(errors, fields) => {
if (errors) {
console.log("Validation failed:", errors);
} else {
console.log("Validation passed:", fields);
}
}
);
// Validation with options
await schema.validate(
{ name: "", age: 25 },
{
suppressWarning: true,
first: false, // Report all errors
keys: ["name"], // Only validate specific fields
messages: {
required: "This field is mandatory"
}
}
);Register a custom validator function for a specific type.
/**
* Register a custom validator function for a type
* @param type - The validation type name
* @param validator - The validator function
* @throws Error if validator is not a function
*/
static register(type: string, validator: Function): void;Usage Example:
// Register custom phone validator
Schema.register("phone", (rule, value, callback, source, options) => {
const phoneRegex = /^\+?[\d\s\-\(\)]{10,}$/;
if (!phoneRegex.test(value)) {
callback("Invalid phone number format");
} else {
callback();
}
});
// Use in rules
const schema = new Schema({
phone: { type: "phone", required: true }
});Static reference to the warning utility function.
static warning: (type: string, errors: SyncErrorType[]) => void;Static reference to default validation messages.
static messages: InternalValidateMessages;Static reference to all built-in validator functions.
static validators: Record<string, ExecuteValidator>;Usage Example:
// Access built-in validators
console.log(Object.keys(Schema.validators));
// Output: ["string", "number", "boolean", "email", "url", ...]
// Use built-in validator directly
const stringValidator = Schema.validators.string;Determines the validation type for a rule, with automatic pattern detection.
/**
* Get the validation type for a rule
* @param rule - The rule to analyze
* @returns The rule type string
* @throws Error if type is unknown
*/
getType(rule: InternalRuleItem): string;Retrieves the appropriate validation method for a rule.
/**
* Get the validation method for a rule
* @param rule - The rule to get validator for
* @returns The validator function or undefined
*/
getValidationMethod(rule: InternalRuleItem): ExecuteValidator | undefined;