joi-schema-validator
Version:
A world-class Joi validation error formatter for structured, user-friendly error handling.
53 lines (52 loc) • 2.31 kB
TypeScript
import { Schema, ValidationOptions } from 'joi';
import { formatError } from './formatter';
import { ErrorMessages } from './types';
import { Request, Response, NextFunction } from 'express';
/**
* Enhanced Type Safety for Validation Results
* This interface ensures that validation results are strongly typed.
*/
export interface ValidationResult<T> {
value: T;
error?: ReturnType<typeof formatError> | null;
}
/**
* validate
* Synchronous validation function.
*
* Field-Level Error Message Overrides & Custom Error Formatting Options:
* The error messages are formatted using the provided (or default) error messages.
* You can supply field-specific messages in the custom messages object. For instance:
* { 'name.string.min': 'Name must have at least {#limit} characters.' }
*
* @param schema - Joi schema definition.
* @param input - Data to validate.
* @param options - Optional Joi validation options.
* @param messages - Custom error message overrides.
* @returns ValidationResult<T>
*/
export declare function validate<T>(schema: Schema, input: any, messages?: ErrorMessages, options?: ValidationOptions): ValidationResult<T>;
/**
* validateAsync
* Async Validation Support:
* Handles asynchronous Joi validation, which is useful when validations involve async operations,
* such as database lookups or external API calls.
*
* @param schema - Joi schema definition.
* @param input - Data to validate.
* @param options - Optional Joi validation options.
* @param messages - Custom error message overrides.
* @returns Promise resolving to ValidationResult<T>
*/
export declare function validateAsync<T>(schema: Schema, input: any, messages?: ErrorMessages, options?: ValidationOptions): Promise<ValidationResult<T>>;
/**
* validateMiddleware
* Express Middleware for Validation:
* Returns an Express middleware that validates req.body against the provided schema.
* If validation fails, it sends a 400 response with formatted errors.
*
* @param schema - Joi schema definition.
* @param messages - Custom error message overrides.
* @returns Express middleware function.
*/
export declare function validateMiddleware(schema: Schema, messages?: ErrorMessages): (req: Request, res: Response, next: NextFunction) => Response<any, Record<string, any>> | undefined;