UNPKG

7.62 kBTypeScriptView Raw
1import { CustomSanitizer, CustomValidator, ErrorMessage, FieldMessageFactory, Location, Middleware, Request, ValidationError } from './base';
2import { ContextRunner, ValidationChain } from './chain';
3import { MatchedDataOptions } from './matched-data';
4import { checkExact } from './middlewares/exact';
5import { OneOfOptions } from './middlewares/one-of';
6import { DefaultSchemaKeys, ExtensionSanitizerSchemaOptions, ExtensionValidatorSchemaOptions, ParamSchema, RunnableValidationChains } from './middlewares/schema';
7import { ErrorFormatter, Result } from './validation-result';
8type CustomValidatorsMap = Record<string, CustomValidator>;
9type CustomSanitizersMap = Record<string, CustomSanitizer>;
10type CustomOptions<E = ValidationError> = {
11 errorFormatter?: ErrorFormatter<E>;
12};
13/**
14 * A validation chain that contains some extension validators/sanitizers.
15 *
16 * Built-in methods return the same chain type so that chaining using more of the extensions is
17 * possible.
18 *
19 * @example
20 * ```
21 * function createChain(chain: ValidationChainWithExtensions<'isAllowedDomain' | 'removeEmailAttribute'>) {
22 * return chain
23 * .isEmail()
24 * .isAllowedDomain()
25 * .trim()
26 * .removeEmailAttribute();
27 * }
28 * ```
29 */
30export type ValidationChainWithExtensions<T extends string> = Middleware & {
31 [K in keyof ValidationChain]: ValidationChain[K] extends (...args: infer A) => ValidationChain ? (...params: A) => ValidationChainWithExtensions<T> : ValidationChain[K];
32} & {
33 [K in T]: () => ValidationChainWithExtensions<T>;
34};
35/**
36 * Schema of validations/sanitizations for a field, including extension validators/sanitizers
37 */
38export type ParamSchemaWithExtensions<V extends string, S extends string, T extends string = DefaultSchemaKeys> = {
39 [K in keyof ParamSchema<T> | V | S]?: K extends V ? ExtensionValidatorSchemaOptions : K extends S ? ExtensionSanitizerSchemaOptions : K extends keyof ParamSchema<T> ? ParamSchema<T>[K] : never;
40};
41/**
42 * Type of a validation chain created by a custom ExpressValidator instance.
43 *
44 * @example
45 * ```
46 * const myExpressValidator = new ExpressValidator({
47 * isAllowedDomain: value => value.endsWith('@gmail.com')
48 * });
49 *
50 * type MyCustomValidationChain = CustomValidationChain<typeof myExpressValidator>
51 * function createMyCustomChain(): MyCustomValidationChain {
52 * return myExpressValidator.body('email').isAllowedDomain();
53 * }
54 * ```
55 */
56export type CustomValidationChain<T extends ExpressValidator<any, any, any>> = T extends ExpressValidator<infer V, infer S, any> ? ValidationChainWithExtensions<Extract<keyof V | keyof S, string>> : never;
57/**
58 * Mapping from field name to a validations/sanitizations schema, including extensions from an
59 * ExpressValidator instance.
60 */
61export type CustomSchema<T extends ExpressValidator<any, any, any>, K extends string = DefaultSchemaKeys> = T extends ExpressValidator<infer V, infer S, any> ? Record<string, ParamSchemaWithExtensions<Extract<keyof V, string>, Extract<keyof S, string>, K>> : never;
62export declare class ExpressValidator<V extends CustomValidatorsMap = {}, S extends CustomSanitizersMap = {}, E = ValidationError> {
63 private readonly validators?;
64 private readonly sanitizers?;
65 private readonly options?;
66 private readonly validatorEntries;
67 private readonly sanitizerEntries;
68 constructor(validators?: V | undefined, sanitizers?: S | undefined, options?: CustomOptions<E> | undefined);
69 private createChain;
70 buildCheckFunction(locations: Location[]): (fields?: string | string[], message?: FieldMessageFactory | ErrorMessage) => CustomValidationChain<this>;
71 /**
72 * Creates a middleware/validation chain for one or more fields that may be located in
73 * any of the following:
74 *
75 * - `req.body`
76 * - `req.cookies`
77 * - `req.headers`
78 * - `req.params`
79 * - `req.query`
80 *
81 * @param fields a string or array of field names to validate/sanitize
82 * @param message an error message to use when failed validations don't specify a custom message.
83 * Defaults to `Invalid Value`.
84 */
85 readonly check: (fields?: string | string[], message?: FieldMessageFactory | ErrorMessage) => CustomValidationChain<this>;
86 /**
87 * Same as {@link ExpressValidator.check}, but only validates in `req.body`.
88 */
89 readonly body: (fields?: string | string[], message?: FieldMessageFactory | ErrorMessage) => CustomValidationChain<this>;
90 /**
91 * Same as {@link ExpressValidator.check}, but only validates in `req.cookies`.
92 */
93 readonly cookie: (fields?: string | string[], message?: FieldMessageFactory | ErrorMessage) => CustomValidationChain<this>;
94 /**
95 * Same as {@link ExpressValidator.check}, but only validates in `req.headers`.
96 */
97 readonly header: (fields?: string | string[], message?: FieldMessageFactory | ErrorMessage) => CustomValidationChain<this>;
98 /**
99 * Same as {@link ExpressValidator.check}, but only validates in `req.params`.
100 */
101 readonly param: (fields?: string | string[], message?: FieldMessageFactory | ErrorMessage) => CustomValidationChain<this>;
102 /**
103 * Same as {@link ExpressValidator.check}, but only validates in `req.query`.
104 */
105 readonly query: (fields?: string | string[], message?: FieldMessageFactory | ErrorMessage) => CustomValidationChain<this>;
106 /**
107 * Checks whether the request contains exactly only those fields that have been validated.
108 *
109 * This method is here for convenience; it does exactly the same as `checkExact`.
110 *
111 * @see {@link checkExact}
112 */
113 readonly checkExact: typeof checkExact;
114 /**
115 * Creates an express middleware with validations for multiple fields at once in the form of
116 * a schema object.
117 *
118 * @param schema the schema to validate.
119 * @param defaultLocations which locations to validate in each field. Defaults to every location.
120 */
121 readonly checkSchema: <T extends string = DefaultSchemaKeys>(schema: CustomSchema<this, T>, locations?: Location[]) => RunnableValidationChains<CustomValidationChain<this>>;
122 /**
123 * Creates a middleware that will ensure that at least one of the given validation chains
124 * or validation chain groups are valid.
125 *
126 * If none are, a single error of type `alternative` is added to the request,
127 * with the errors of each chain made available under the `nestedErrors` property.
128 *
129 * @param chains an array of validation chains to check if are valid.
130 * If any of the items of `chains` is an array of validation chains, then all of them
131 * must be valid together for the request to be considered valid.
132 */
133 oneOf(chains: (CustomValidationChain<this> | CustomValidationChain<this>[])[], options?: OneOfOptions): Middleware & ContextRunner;
134 /**
135 * Extracts the validation errors of an express request using the default error formatter of this
136 * instance.
137 *
138 * @see {@link validationResult()}
139 * @param req the express request object
140 * @returns a `Result` which will by default use the error formatter passed when
141 * instantiating `ExpressValidator`.
142 */
143 readonly validationResult: (req: Request) => Result<E>;
144 /**
145 * Extracts data validated or sanitized from the request, and builds an object with them.
146 *
147 * This method is a shortcut for `matchedData`; it does nothing different than it.
148 *
149 * @see {@link matchedData}
150 */
151 matchedData(req: Request, options?: Partial<MatchedDataOptions>): Record<string, any>;
152}
153export {};