@resk/core
Version:
An innovative TypeScript framework that empowers developers to build applications with a fully decorator-based architecture for efficient resource management. By combining the power of decorators with a resource-oriented design, DecorRes enhances code cla
123 lines (122 loc) • 6.11 kB
TypeScript
import { IValidatorRule, IValidatorValidateOptions, IValidatorRuleMap, IValidatorRuleName, IValidatorRuleFunction, IValidatorSanitizedRules } from "./types";
import { IClassConstructor } from "../types";
/**
* @class Validator
* A class that provides methods for validating elements based on defined rules.
*
* The `Validator` class allows you to define validation rules, sanitize them,
* and validate values against those rules. It supports both synchronous and asynchronous
* validation, making it flexible for various use cases.
*/
export declare class Validator {
private static readonly RULES_METADATA_KEY;
/**
* Register a new validation rule.
* @template ParamType The type of the parameters that the rule function accepts.
* @param name The name of the rule.
* @param handler The validation function.
*/
static registerRule<ParamType extends Array<any> = Array<any>>(name: IValidatorRuleName, handler: IValidatorRuleFunction<ParamType>): void;
/**
* A static getter that returns a record of validation rules.
*
* @returns {IValidatorRuleMap} An object containing validation rules.
*/
static getRules(): IValidatorRuleMap;
/***
* returns the separators for the validation errors.
* @returns {IDict} the separators for the validation errors.
*/
static get separators(): {
multiple: string;
single: string;
};
/**
* Retrieves a validation rule by its name.
*
* @param {IValidatorRuleName} rulesName - The name of the validation rule to retrieve.
* @returns {IValidatorRuleFunction | undefined} The validation rule if found, otherwise undefined.
*/
static getRule<ParamType extends Array<any> = Array<any>>(rulesName: IValidatorRuleName): IValidatorRuleFunction<ParamType> | undefined;
/**
* Sanitizes a set of validation rules and returns an array of rules.
*
* This method takes a list of validation rules, which can be in various formats,
* and returns an array of sanitized rules ready for validation.
*
* @param {IValidatorValidateOptions["rules"]} rules - The list of validation rules. The rules can be:
* - An array of rules (e.g., ["required", "minLength[2]", "maxLength[10]"]).
*
* @returns {{sanitizedRules:IValidatorSanitizedRules,invalidRules:IValidatorRule[]}}
*/
static sanitizeRules(rules?: IValidatorValidateOptions["rules"]): {
sanitizedRules: IValidatorSanitizedRules;
invalidRules: IValidatorRule[];
};
/**
* Validates a value against the specified validation rules.
*
* This method takes a value and a set of validation rules, and performs validation.
* It returns a promise that resolves if the validation passes, or rejects with an error
* message if the validation fails.
*
* @param {IValidatorValidateOptions} options - The options for validation, including:
* - `value`: The value to validate.
* - `rules`: An array of validation rules to apply.
* - `...extra`: Any additional options that may be applied.
*
* @returns {Promise<any>} A promise that resolves with the validation result or rejects with an error.
*
* ### Example:
* ```typescript
* Validator.validate({
* rules: "minLength[5]|maxLength[10]",
* value: "test",
* }).then(result => {
* console.log("Validation passed:", result);
* }).catch(error => {
* console.error("Validation failed:", error);
* });
* ```
*/
static validate({ rules, value, ...extra }: IValidatorValidateOptions): Promise<IValidatorValidateOptions>;
/***
* Validate a target decorated using the ValidatorDecorator.
* @param {IClassConstructor} target - The target class.
* @param {Partial<Record<keyof InstanceType<T>, any>>} data - The data to validate.
* @param {IValidatorValidateTargetOptions} options - The options for validating the target.
* @returns {Promise<IValidatorValidateTargetOptions>} A promise that resolves with the validated data.
* @example
* // Validate a target decorated with the ValidatorDecorator.
* const validatedData = await Validator.validateTarget(MyClass, data);
* console.log(validatedData);
*/
static validateTarget<T extends IClassConstructor = any>(target: T, data: Partial<Record<keyof InstanceType<T>, any>>, options?: {
errorMessageBuilder?: (translatedPropertyName: string, error: string, builderOptions: {
propertyName: string;
translatedPropertyName: string;
message: string;
ruleName: string;
ruleParams: any[];
value: any;
separators: {
multiple: string;
single: string;
};
data: Partial<Record<keyof InstanceType<T>, any>>;
}) => string;
}): Promise<{
data: Partial<Record<keyof InstanceType<T>, any>>;
}>;
static getTargetRules<T extends IClassConstructor = any>(target: T): Record<keyof InstanceType<T>, IValidatorRule[]>;
static getValidateTargetOptions<T extends IClassConstructor = any>(target: T): Parameters<typeof Validator.validateTarget>[2];
static createDecorator<RuleParamsType extends Array<any> = Array<any>>(ruleFunction: IValidatorRuleFunction<RuleParamsType>): (params: RuleParamsType) => PropertyDecorator;
static createPropertyDecorator<RuleParamsType extends Array<any> = Array<any>>(rule: IValidatorRule<RuleParamsType> | IValidatorRule<RuleParamsType>[]): PropertyDecorator;
}
export declare const ValidatorIsNumber: PropertyDecorator;
export declare const ValidatorIsRequired: PropertyDecorator;
export declare const ValidatorIsEmail: PropertyDecorator;
export declare const ValidatorIsUrl: PropertyDecorator;
export declare const ValidatorIsFileName: PropertyDecorator;
export declare const ValidatorIsNonNullString: PropertyDecorator;
export declare function ValidatorValidateTargetOptions(options: Parameters<typeof Validator.validateTarget>[2]): ClassDecorator;