CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-async-validator

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

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

schema.mddocs/

Schema Management

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

Capabilities

Schema Constructor

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 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 }
});

Configure Messages

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"
  }
});

Validate Data

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"
    }
  }
);

Static Methods

Register Custom Validator

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 Properties

Warning Function

Static reference to the warning utility function.

static warning: (type: string, errors: SyncErrorType[]) => void;

Default Messages

Static reference to default validation messages.

static messages: InternalValidateMessages;

Built-in Validators

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;

Internal Methods

Get Rule Type

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;

Get Validation Method

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;

docs

error-handling.md

index.md

messages.md

rules.md

schema.md

validation-types.md

tile.json