UNPKG

17.8 kBTypeScriptView Raw
1// Type definitions for express-validator 3.0.0
2// Project: https://github.com/ctavan/express-validator
3// Definitions by: Ayman Nedjmeddine <https://github.com/IOAyman>, Nathan Ridley <https://github.com/axefrog/>, Jonathan Häberle <http://dreampulse.de>, Peter Harris <https://github.com/codeanimal/>
4// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
5
6///<reference types="express"/>
7///<reference types="bluebird"/>
8
9// Add RequestValidation Interface on to Express's Request Interface.
10declare namespace Express {
11 interface Request extends ExpressValidator.RequestValidation {}
12}
13
14// External express-validator module.
15declare module "express-validator" {
16 import express = require('express');
17
18 /**
19 * @param options see: https://github.com/ctavan/express-validator#middleware-options
20 * @constructor
21 */
22 function ExpressValidator(options?: ExpressValidator.Options.ExpressValidatorOptions): express.RequestHandler;
23
24 export = ExpressValidator;
25}
26
27// Internal Module.
28declare namespace ExpressValidator {
29
30 export type URLProtocol = 'http' | 'https' | 'ftp'
31 export type UUIDVersion = 3 | 4 | 5 | 'all'
32 export type IPVersion = 4 | 6
33 export type AlphaLocale = 'ar' | 'ar-AE' | 'ar-BH' | 'ar-DZ' | 'ar-EG' | 'ar-IQ' | 'ar-JO' | 'ar-KW' | 'ar-LB' | 'ar-LY' | 'ar-MA' | 'ar-QA' | 'ar-QM' | 'ar-SA' | 'ar-SD' | 'ar-SY' | 'ar-TN' | 'ar-YE' | 'cs-CZ' | 'da-DK' | 'de-DE' | 'en-AU' | 'en-GB' | 'en-HK' | 'en-IN' | 'en-NZ' | 'en-US' | 'en-ZA' | 'en-ZM' | 'es-ES' | 'fr-FR' | 'hu-HU' | 'nl-NL' | 'pl-PL' | 'pt-BR' | 'pt-PT' | 'ru-RU' | 'sr-RS' | 'sr-RS@latin' | 'tr-TR' | 'uk-UA'
34 export type AlphanumericLocale = 'ar' | 'ar-AE' | 'ar-BH' | 'ar-DZ' | 'ar-EG' | 'ar-IQ' | 'ar-JO' | 'ar-KW' | 'ar-LB' | 'ar-LY' | 'ar-MA' | 'ar-QA' | 'ar-QM' | 'ar-SA' | 'ar-SD' | 'ar-SY' | 'ar-TN' | 'ar-YE' | 'cs-CZ' | 'da-DK' | 'de-DE' | 'en-AU' | 'en-GB' | 'en-HK' | 'en-IN' | 'en-NZ' | 'en-US' | 'en-ZA' | 'en-ZM' | 'es-ES' | 'fr-FR' | 'fr-BE' | 'hu-HU' | 'nl-BE' | 'nl-NL' | 'pl-PL' | 'pt-BR' | 'pt-PT' | 'ru-RU' | 'sr-RS' | 'sr-RS@latin' | 'tr-TR' | 'uk-UA'
35 export type MobilePhoneLocal = 'ar-DZ' | 'ar-SA' | 'ar-SY' | 'cs-CZ' | 'de-DE' | 'da-DK' | 'el-GR' | 'en-AU' | 'en-GB' | 'en-HK' | 'en-IN' | 'en-NZ' | 'en-US' | 'en-CA' | 'en-ZA' | 'en-ZM' | 'es-ES' | 'fi-FI' | 'fr-FR' | 'hu-HU' | 'it-IT' | 'ja-JP' | 'ms-MY' | 'nb-NO' | 'nn-NO' | 'pl-PL' | 'pt-PT' | 'ru-RU' | 'sr-RS' | 'tr-TR' | 'vi-VN' | 'zh-CN' | 'zh-TW'
36 export type Location = 'body' | 'params' | 'query' | 'headers' // TODO add cookies if #292 is accepted
37
38 export type ValidationSchema = {
39 [param: string]:
40 ExpressValidator.Options.ValidationSchemaParamOptions // standard validators
41 | // or
42 { [customValidator: string]: ExpressValidator.Options.ValidatorSchemaOptions } // custom ones
43 }
44
45 interface ValidatorFunction {
46 (item: string | string[], message?: string): Validator;
47 (schema: {}): Validator;
48 }
49 /**
50 * This one's used for RegexRoutes
51 * @see https://github.com/ctavan/express-validator#regex-routes
52 */
53 interface ValidatorFunctionRegExp extends ValidatorFunction { (matchIndex: number, message?: string): Validator; }
54 interface SanitizerFunction { (item: string): Sanitizer; }
55 interface Dictionary<T> { [key: string]: T; }
56 interface Result {
57 /**
58 * @return A boolean determining whether there were errors or not.
59 */
60 isEmpty(): boolean
61 /**
62 * @return All errors for all validated parameters will be included, unless you specify that you want only the first
63 * error of each param by invoking `result.useFirstErrorOnly()`.
64 */
65 array(): MappedError[]
66 /**
67 * @return An object of errors, where the key is the parameter name, and the value is an error object as returned by
68 * the error formatter.
69 * Because of historical reasons, by default this method will return the last error of each parameter.
70 * You can change this behavior by invoking result.useFirstErrorOnly(), so the first error is returned instead.
71 */
72 mapped(): Dictionary<MappedError>
73 /**
74 * Sets the `firstErrorOnly` flag of this result object, which modifies the way other methods like `result.array()`
75 * and `result.mapped()` work.
76 */
77 useFirstErrorOnly(): Result
78 /**
79 * Useful for dealing with the validation errors in the catch block of a try..catch or promise.
80 *
81 * @throws If there are errors, throws an Error object which is decorated with the same API as the validation
82 * result object.
83 */
84 throw(): Result
85 }
86
87 export interface RequestValidation {
88 assert: ValidatorFunctionRegExp;
89 validate: ValidatorFunctionRegExp;
90 check: ValidatorFunctionRegExp;
91 checkBody: ValidatorFunction;
92 checkCookies: ValidatorFunction;
93 checkHeaders: ValidatorFunction;
94 checkParams: ValidatorFunction;
95 checkQuery: ValidatorFunction;
96
97 filter: SanitizerFunction;
98 sanitize: SanitizerFunction;
99 sanitizeBody: SanitizerFunction;
100 sanitizeQuery: SanitizerFunction;
101 sanitizeParams: SanitizerFunction;
102 sanitizeHeaders: SanitizerFunction;
103 sanitizeCookies: SanitizerFunction;
104
105 /**
106 * @deprecated
107 * @param mapped Will cause the validator to return an object that maps parameter to error.
108 * @return Synchronous errors in the form of an array. If there are no errors, the returned value is false.
109 */
110 validationErrors(mapped?: boolean): Dictionary<MappedError> | MappedError[];
111 /**
112 * @deprecated
113 * @param mapped Will cause the validator to return an object that maps parameter to error.
114 * @return Synchronous errors in the form of an array. If there are no errors, the returned value is false.
115 */
116 validationErrors<T>(mapped?: boolean): Dictionary<T> | T[];
117 /**
118 * @deprecated
119 * @param mapped Whether to map parameters to errors or not.
120 */
121 asyncValidationErrors(mapped?: boolean): Promise<MappedError[] | Dictionary<MappedError>>;
122 /**
123 * @deprecated
124 * @param mapped Whether to map parameters to errors or not.
125 */
126 asyncValidationErrors<T>(mapped?: boolean): Promise<T[] | Dictionary<T>>;
127 /**
128 * @return Promise<Result> A Promise which resolves to a result object.
129 */
130 getValidationResult(): Promise<Result>
131 }
132
133 export interface Validator {
134
135 /*
136 * Hi fellow contributor,
137 * TODO if you add a validator here, please add it also to ValidationSchemaParamOptions
138 * preferably in the same order/position, just to make it easier for comparision.
139 */
140
141 isEmail(options?: ExpressValidator.Options.IsEmailOptions): Validator;
142 isURL(options?: ExpressValidator.Options.IsURLOptions): Validator;
143 isMACAddress(): Validator;
144 /**
145 *
146 * @param version IP version number 4 or 6
147 */
148 isIP(version?: IPVersion): Validator;
149 isFQDN(options?: ExpressValidator.Options.IsFQDNOptions): Validator;
150 isBoolean(): Validator;
151 /**
152 * @param locale Optional. Defaults to en-US
153 */
154 isAlpha(locale?: AlphaLocale): Validator;
155 /**
156 * @param locale Optional. Defaults to en-US
157 */
158 isAlphanumeric(locale?: AlphanumericLocale): Validator;
159 isNumeric(): Validator;
160 isLowercase(): Validator;
161 isUppercase(): Validator;
162 isAscii(): Validator;
163 isFullWidth(): Validator;
164 isHalfWidth(): Validator;
165 isVariableWidth(): Validator;
166 isMultibyte(): Validator;
167 isSurrogatePair(): Validator;
168 isInt(options?: ExpressValidator.Options.IsIntOptions): Validator;
169 isFloat(options?: ExpressValidator.Options.MinMaxExtendedOptions): Validator;
170 isDecimal(): Validator;
171 isHexadecimal(): Validator;
172 isDivisibleBy(num: number): Validator;
173 isHexColor(): Validator;
174 isMD5(): Validator;
175 isJSON(): Validator;
176 isEmpty(): Validator;
177 isLength(options: ExpressValidator.Options.MinMaxOptions): Validator;
178 isByteLength(options: ExpressValidator.Options.MinMaxOptions): Validator;
179 /**
180 * @param version 3, 4, 5 or 'all'. Default is 'all'.
181 * @see http://en.wikipedia.org/wiki/Universally_unique_identifier
182 */
183 isUUID(version?: UUIDVersion): Validator;
184 /**
185 * @see https://docs.mongodb.com/manual/reference/bson-types/#objectid
186 */
187 isMongoId(): Validator;
188 isDate(): Validator;
189 /**
190 * @param date Optional. Default to now.
191 */
192 isAfter(date?: Date): Validator;
193 /**
194 * @param date Optional. Default to now.
195 */
196 isBefore(date?: Date): Validator;
197 isIn(options: string | string[]): Validator;
198 isCreditCard(): Validator;
199 isISIN(): Validator;
200 /**
201 * @param version
202 * @see https://en.wikipedia.org/wiki/International_Standard_Book_Number
203 */
204 isISBN(version?: number): Validator;
205 /**
206 * @param options
207 * @see https://en.wikipedia.org/wiki/International_Standard_Serial_Number
208 */
209 isISSN(options?: ExpressValidator.Options.IsISSNOptions): Validator
210 isMobilePhone(locale: MobilePhoneLocal): Validator;
211 isCurrency(options: ExpressValidator.Options.IsCurrencyOptions): Validator;
212 /**
213 * @see https://en.wikipedia.org/wiki/ISO_8601
214 */
215 isISO8601(): Validator;
216 /**
217 * @see https://en.wikipedia.org/wiki/Base64
218 */
219 isBase64(): Validator;
220 /**
221 * @see https://en.wikipedia.org/wiki/Data_URI_scheme
222 */
223 isDataURI(): Validator;
224 isWhitelisted(chars: string | string[]): Validator;
225
226
227 // Additional Validators provided by validator.js
228
229 equals(equals: any): Validator;
230 contains(str: string): Validator;
231 matches(pattern: RegExp | string, modifiers?: string): Validator;
232
233
234 // Additional ValidatorChain.prototype.* validators
235
236 notEmpty(): Validator;
237 len(options: ExpressValidator.Options.MinMaxOptions): Validator;
238 optional(options?: ExpressValidator.Options.OptionalOptions): Validator;
239 withMessage(message: string): Validator;
240 }
241
242 interface Sanitizer {
243 /**
244 * Convert the input string to a date, or null if the input is not a date.
245 */
246 toDate(): Sanitizer;
247 /**
248 * Convert the input string to a float, or NaN if the input is not a float.
249 */
250 toFloat(): Sanitizer;
251 /**
252 * Convert the input string to a float, or NaN if the input is not a float.
253 */
254 toInt(radix?: number): Sanitizer;
255 /**
256 * Cnvert the input string to a boolean.
257 * Everything except for '0', 'false' and '' returns true.
258 * @param strict If true, only '1' and 'true' return true.
259 */
260 toBoolean(strict?: boolean): Sanitizer;
261 /**
262 * Trim characters (whitespace by default) from both sides of the input.
263 * @param chars Defaults to whitespace
264 */
265 trim(chars: string): Sanitizer;
266 ltrim(chars: string): Sanitizer;
267 rtrim(chars: string): Sanitizer;
268 /**
269 * Remove characters with a numerical value < 32 and 127, mostly control characters.
270 * Unicode-safe in JavaScript.
271 * @param keep_new_lines If true, newline characters are preserved (\n and \r, hex 0xA and 0xD).
272 */
273 stripLow(keep_new_lines?: boolean): Sanitizer;
274 /**
275 * Escape &, <, >, and "
276 */
277 escape(): Sanitizer;
278 /**
279 * Replaces HTML encoded entities with <, >, &, ', " and /.
280 */
281 unescape(): Sanitizer;
282 blacklist(chars: string): Sanitizer;
283 whitelist(chars: string): Sanitizer;
284
285 normalizeEmail(options?: ExpressValidator.Options.NormalizeEmailOptions): Sanitizer;
286 }
287
288 interface MappedError {
289 param: string;
290 msg: string;
291 value: string;
292 }
293}
294
295declare namespace ExpressValidator.Options {
296
297 export interface ExpressValidatorOptions {
298 customValidators?: { [validatorName: string]: (...value: any[]) => boolean }
299 customSanitizers?: { [sanitizername: string]: (value: any) => any }
300 errorFormatter?: (param: string, msg: string, value: any) => {param: string, msg: string, value: any}
301 }
302
303
304 interface ValidatorSchemaOptions {
305 options?: any[]
306 errorMessage?: string
307 }
308
309 interface ValidationSchemaParamOptions {
310 in?: Location
311 errorMessage?: string
312
313 // Additional ValidatorChain.prototype.* validators
314 optional?: boolean | { checkFalsy: boolean }
315 notEmpty?: boolean | { errorMessage: string }
316 len?: ValidatorSchemaOptions
317
318 // exported from validator.js
319 isEmail?: ValidatorSchemaOptions
320 isURL?: ValidatorSchemaOptions
321 isMACAddress?: ValidatorSchemaOptions
322 isIP?: ValidatorSchemaOptions
323 isFQDN?: ValidatorSchemaOptions
324 isBoolean?: ValidatorSchemaOptions
325 isAlpha?: ValidatorSchemaOptions
326 isAlphanumeric?: ValidatorSchemaOptions
327 isNumeric?: ValidatorSchemaOptions
328 isLowercase?: ValidatorSchemaOptions
329 isUppercase?: ValidatorSchemaOptions
330 isAscii?: ValidatorSchemaOptions
331 isFullWidth?: ValidatorSchemaOptions
332 isHalfWidth?: ValidatorSchemaOptions
333 isVariableWidth?: ValidatorSchemaOptions
334 isMultibyte?: ValidatorSchemaOptions
335 isSurrogatePair?: ValidatorSchemaOptions
336 isInt?: ValidatorSchemaOptions
337 isFloat?: ValidatorSchemaOptions
338 isDecimal?: ValidatorSchemaOptions
339 isHexadecimal?: ValidatorSchemaOptions
340 isDivisibleBy?: ValidatorSchemaOptions
341 isHexColor?: ValidatorSchemaOptions
342 isMD5?: ValidatorSchemaOptions
343 isJSON?: ValidatorSchemaOptions
344 isEmpty?: ValidatorSchemaOptions
345 isLength?: ValidatorSchemaOptions
346 isByteLength?: ValidatorSchemaOptions
347 isUUID?: ValidatorSchemaOptions
348 isMongoId?: ValidatorSchemaOptions
349 isDate?: ValidatorSchemaOptions
350 isAfter?: ValidatorSchemaOptions
351 isBefore?: ValidatorSchemaOptions
352 isIn?: ValidatorSchemaOptions
353 isCreditCard?: ValidatorSchemaOptions
354 isISIN?: ValidatorSchemaOptions
355 isISBN?: ValidatorSchemaOptions
356 isISSN?: ValidatorSchemaOptions
357 isMobilePhone?: ValidatorSchemaOptions
358 isCurrency?: ValidatorSchemaOptions
359 isISO8601?: ValidatorSchemaOptions
360 isBase64?: ValidatorSchemaOptions
361 isDataURI?: ValidatorSchemaOptions
362 isWhitelisted?: ValidatorSchemaOptions
363
364 // Additional Validators provided by validator.js
365 equals?: ValidatorSchemaOptions
366 contains?: ValidatorSchemaOptions
367 matches?: ValidatorSchemaOptions
368 }
369
370
371 // VALIDATORS
372
373 interface MinMaxOptions {
374 min?: number;
375 max?: number;
376 }
377
378 interface MinMaxExtendedOptions extends MinMaxOptions {
379 lt?: number;
380 gt?: number;
381 }
382
383 interface IsIntOptions extends MinMaxExtendedOptions {
384 allow_leading_zeroes?: boolean;
385 }
386
387 /**
388 * defaults to
389 * {
390 * allow_display_name: false,
391 * require_display_name: false,
392 * allow_utf8_local_part: true,
393 * require_tld: true
394 * }
395 */
396 interface IsEmailOptions {
397 allow_display_name?: boolean;
398 allow_utf8_local_part?: boolean;
399 require_tld?: boolean;
400 }
401
402 /**
403 * defaults to
404 * {
405 * protocols: ['http','https','ftp'],
406 * require_tld: true,
407 * require_protocol: false,
408 * require_host: true,
409 * require_valid_protocol: true,
410 * allow_underscores: false,
411 * host_whitelist: false,
412 * host_blacklist: false,
413 * allow_trailing_dot: false,
414 * allow_protocol_relative_urls: false
415 * }
416 */
417 interface IsURLOptions {
418 protocols?: URLProtocol[];
419 require_tld?: boolean;
420 require_protocol?: boolean;
421 require_host?: boolean;
422 require_valid_protocol?: boolean;
423 allow_underscores?: boolean;
424 host_whitelist?: (string | RegExp)[];
425 host_blacklist?: (string | RegExp)[];
426 allow_trailing_dot?: boolean;
427 allow_protocol_relative_urls?: boolean;
428 }
429
430 /**
431 * defaults to
432 * {
433 * require_tld: true,
434 * allow_underscores: false,
435 * allow_trailing_dot: false
436 * }
437 */
438 interface IsFQDNOptions {
439 require_tld?: boolean;
440 allow_underscores?: boolean;
441 allow_trailing_dot?: boolean;
442 }
443
444 /**
445 * defaults to
446 * {
447 * case_sensitive: false,
448 * require_hyphen: false
449 * }
450 */
451 interface IsISSNOptions {
452 case_sensitive?: boolean
453 require_hyphen?: boolean
454 }
455
456 /**
457 * defaults to
458 * {
459 * symbol: '$',
460 * require_symbol: false,
461 * allow_space_after_symbol: false,
462 * symbol_after_digits: false,
463 * allow_negatives: true,
464 * parens_for_negatives: false,
465 * negative_sign_before_digits: false,
466 * negative_sign_after_digits: false,
467 * allow_negative_sign_placeholder: false,
468 * thousands_separator: ',',
469 * decimal_separator: '.',
470 * allow_space_after_digits: false
471 * }
472 */
473 interface IsCurrencyOptions {
474 symbol?: string;
475 require_symbol?: boolean;
476 allow_space_after_symbol?: boolean;
477 symbol_after_digits?: boolean;
478 allow_negatives?: boolean;
479 parens_for_negatives?: boolean;
480 negative_sign_before_digits?: boolean;
481 negative_sign_after_digits?: boolean;
482 allow_negative_sign_placeholder?: boolean;
483 thousands_separator?: string;
484 decimal_separator?: string;
485 allow_space_after_digits?: boolean;
486 }
487
488 interface OptionalOptions {
489 checkFalsy?: boolean;
490 }
491
492
493 // SANITIZERS
494
495 /**
496 * Defaults to
497 * {
498 * all_lowercase: true
499 * gmail_lowercase: true
500 * gmail_remove_dots: true
501 * gmail_remove_subaddress: true
502 * gmail_convert_googlemaildotcom: true
503 * outlookdotcom_lowercase: true
504 * outlookdotcom_remove_subaddress: true
505 * yahoo_lowercase: true
506 * yahoo_remove_subaddress: true
507 * icloud_lowercase: true
508 * icloud_remove_subaddress: true
509 * }
510 */
511 interface NormalizeEmailOptions {
512 all_lowercase?: boolean
513 gmail_lowercase?: boolean
514 gmail_remove_dots?: boolean
515 gmail_remove_subaddress?: boolean
516 gmail_convert_googlemaildotcom?: boolean
517 outlookdotcom_lowercase?: boolean
518 outlookdotcom_remove_subaddress?: boolean
519 yahoo_lowercase?: boolean
520 yahoo_remove_subaddress?: boolean
521 icloud_lowercase?: boolean
522 icloud_remove_subaddress?: boolean
523 }
524}