express-validator

  • Version 7.1.0
  • Published
  • 142 kB
  • 2 dependencies
  • MIT license

Install

npm i express-validator
yarn add express-validator
pnpm add express-validator

Overview

Express middleware for the validator module.

Index

Variables

variable validationResult

const validationResult: ResultFactory<ValidationError> & {
withDefaults: typeof withDefaults;
};
  • Extracts the validation errors of an express request

Functions

function body

body: (
fields?: string | string[] | undefined,
message?: FieldMessageFactory | ErrorMessage | undefined
) => import('..').ValidationChain;
  • Same as , but only validates req.body.

function buildCheckFunction

buildCheckFunction: (
locations: Location[]
) => (
fields?: string | string[] | undefined,
message?: FieldMessageFactory | ErrorMessage | undefined
) => import('..').ValidationChain;
  • Creates a variant of check() that checks the given request locations.

    Example 1

    const checkBodyAndQuery = buildCheckFunction(['body', 'query']);

function check

check: (
fields?: string | string[] | undefined,
message?: FieldMessageFactory | ErrorMessage | undefined
) => import('..').ValidationChain;
  • Creates a middleware/validation chain for one or more fields that may be located in any of the following:

    - req.body - req.cookies - req.headers - req.params - req.query

    Parameter fields

    a string or array of field names to validate/sanitize

    Parameter message

    an error message to use when failed validations don't specify a custom message. Defaults to Invalid Value.

function checkExact

checkExact: (
chains?: CheckExactInput,
opts?: CheckExactOptions
) => Middleware & ContextRunner;
  • Checks whether the request contains exactly only those fields that have been validated.

    Unknown fields, if found, will generate an error of type unknown_fields.

    Parameter chains

    either a single chain, an array of chains, or a mixed array of chains and array of chains. This means that all of the below are valid:

    checkExact(check('foo'))
    checkExact([check('foo'), check('bar')])
    checkExact([check('foo'), check('bar')])
    checkExact(checkSchema({ ... }))
    checkExact([checkSchema({ ... }), check('foo')])

    Parameter opts

function checkSchema

checkSchema: <T extends string = DefaultSchemaKeys>(
schema: Schema<T>,
defaultLocations?: Location[] | undefined
) => RunnableValidationChains<ValidationChain>;
  • Creates an express middleware with validations for multiple fields at once in the form of a schema object.

    Parameter schema

    the schema to validate.

    Parameter defaultLocations

    Returns

cookie: (
fields?: string | string[] | undefined,
message?: FieldMessageFactory | ErrorMessage | undefined
) => import('..').ValidationChain;
  • Same as , but only validates req.cookies.

header: (
fields?: string | string[] | undefined,
message?: FieldMessageFactory | ErrorMessage | undefined
) => import('..').ValidationChain;
  • Same as , but only validates req.headers.

function matchedData

matchedData: <T extends object = Record<string, any>>(
req: Request,
options?: Partial<MatchedDataOptions>
) => T;
  • Extracts data validated or sanitized from the request, and builds an object with them.

    Parameter req

    the express request object

    Parameter options

    Returns

    an object of data that's been validated or sanitized in the passed request

function oneOf

oneOf: (
chains: (ValidationChain | ValidationChain[])[],
options?: OneOfOptions
) => Middleware & ContextRunner;
  • Creates a middleware that will ensure that at least one of the given validation chains or validation chain groups are valid.

    If none are, a single AlternativeValidationError or GroupedAlternativeValidationError is added to the request, with the errors of each chain made available under the nestedErrors property.

    Parameter chains

    an array of validation chains to check if are valid. If any of the items of chains is an array of validation chains, then all of them must be valid together for the request to be considered valid.

function param

param: (
fields?: string | string[] | undefined,
message?: FieldMessageFactory | ErrorMessage | undefined
) => import('..').ValidationChain;
  • Same as , but only validates req.params.

function query

query: (
fields?: string | string[] | undefined,
message?: FieldMessageFactory | ErrorMessage | undefined
) => import('..').ValidationChain;
  • Same as , but only validates req.query.

Classes

class ExpressValidator

class ExpressValidator<
V extends CustomValidatorsMap = {},
S extends CustomSanitizersMap = {},
E = ValidationError
> {}

    constructor

    constructor(
    validators?: CustomValidatorsMap,
    sanitizers?: CustomSanitizersMap,
    options?: CustomOptions<E>
    );

      property body

      readonly body: (
      fields?: string | string[] | undefined,
      message?: FieldMessageFactory | ErrorMessage | undefined
      ) => CustomValidationChain<this>;

      property check

      readonly check: (
      fields?: string | string[] | undefined,
      message?: FieldMessageFactory | ErrorMessage | undefined
      ) => CustomValidationChain<this>;
      • Creates a middleware/validation chain for one or more fields that may be located in any of the following:

        - req.body - req.cookies - req.headers - req.params - req.query

        Parameter fields

        a string or array of field names to validate/sanitize

        Parameter message

        an error message to use when failed validations don't specify a custom message. Defaults to Invalid Value.

      property checkExact

      readonly checkExact: (
      chains?: CheckExactInput,
      opts?: CheckExactOptions
      ) => Middleware & ContextRunner;
      • Checks whether the request contains exactly only those fields that have been validated.

        This method is here for convenience; it does exactly the same as checkExact.

        See Also

      property checkSchema

      readonly checkSchema: <T extends string = DefaultSchemaKeys>(
      schema: CustomSchema<this, T>,
      locations?: Location[] | undefined
      ) => RunnableValidationChains<CustomValidationChain<this>>;
      • Creates an express middleware with validations for multiple fields at once in the form of a schema object.

        Parameter schema

        the schema to validate.

        Parameter defaultLocations

        which locations to validate in each field. Defaults to every location.

      property cookie

      readonly cookie: (
      fields?: string | string[] | undefined,
      message?: FieldMessageFactory | ErrorMessage | undefined
      ) => CustomValidationChain<this>;

      property header

      readonly header: (
      fields?: string | string[] | undefined,
      message?: FieldMessageFactory | ErrorMessage | undefined
      ) => CustomValidationChain<this>;

      property param

      readonly param: (
      fields?: string | string[] | undefined,
      message?: FieldMessageFactory | ErrorMessage | undefined
      ) => CustomValidationChain<this>;

      property query

      readonly query: (
      fields?: string | string[] | undefined,
      message?: FieldMessageFactory | ErrorMessage | undefined
      ) => CustomValidationChain<this>;

      property validationResult

      readonly validationResult: (req: Request) => Result<E>;
      • Extracts the validation errors of an express request using the default error formatter of this instance.

        Parameter req

        the express request object

        Returns

        a Result which will by default use the error formatter passed when instantiating ExpressValidator.

        See Also

      method buildCheckFunction

      buildCheckFunction: (
      locations: Location[]
      ) => (
      fields?: string | string[],
      message?: FieldMessageFactory | ErrorMessage
      ) => CustomValidationChain<this>;

        method matchedData

        matchedData: (
        req: Request,
        options?: Partial<MatchedDataOptions>
        ) => Record<string, any>;
        • Extracts data validated or sanitized from the request, and builds an object with them.

          This method is a shortcut for matchedData; it does nothing different than it.

          See Also

        method oneOf

        oneOf: (
        chains: (CustomValidationChain<this> | CustomValidationChain<this>[])[],
        options?: OneOfOptions
        ) => Middleware & ContextRunner;
        • Creates a middleware that will ensure that at least one of the given validation chains or validation chain groups are valid.

          If none are, a single error of type alternative is added to the request, with the errors of each chain made available under the nestedErrors property.

          Parameter chains

          an array of validation chains to check if are valid. If any of the items of chains is an array of validation chains, then all of them must be valid together for the request to be considered valid.

        class Result

        class Result<T = any> {}
        • The current state of the validation errors in a request.

        constructor

        constructor(formatter: ErrorFormatter<T>, errors: readonly ValidationError[]);

          method array

          array: (options?: ToArrayOptions) => T[];
          • Gets the validation errors as an array.

            Parameter

            options.onlyFirstError whether only the first error of each

          method formatWith

          formatWith: <T2>(formatter: ErrorFormatter<T2>) => Result<T2>;
          • Specifies a function to format errors with.

            Parameter formatter

            the function to use for formatting errors

            Returns

            A new Result instance with the given formatter

          method isEmpty

          isEmpty: () => boolean;
          • Returns

            true if there are no errors, false otherwise

          method mapped

          mapped: () => Record<string, T>;
          • Gets the validation errors as an object. If a field has more than one error, only the first one is set in the resulting object.

            Returns

            an object from field name to error

          method throw

          throw: () => void;
          • Throws an error if there are validation errors.

          Interfaces

          interface ContextRunner

          interface ContextRunner {}

            method run

            run: (
            req: Request,
            options?: ContextRunningOptions
            ) => Promise<ResultWithContext>;
            • Runs the current validation chain.

              Parameter req

              the express request to validate

              Parameter options

              an object of options to customize how the chain will be run

              Returns

              a promise for a Result that resolves when the validation chain has finished

            interface ValidationChain

            interface ValidationChain
            extends Validators<ValidationChain>,
            Sanitizers<ValidationChain>,
            ContextHandler<ValidationChain>,
            ContextRunner {}

              property builder

              builder: ContextBuilder;

                call signature

                (req: Request, res: any, next: (error?: any) => void): void;

                  Type Aliases

                  type AlternativeMessageFactory

                  type AlternativeMessageFactory = (
                  nestedErrors: FieldValidationError[],
                  opts: {
                  req: Request;
                  }
                  ) => any;
                  • A function which creates an error message based on an alternative's nested errors.

                    Parameter nestedErrors

                    The errors from the invalid alternative(s).

                    Parameter opts

                    See Also

                    • oneOf()

                  type AlternativeValidationError

                  type AlternativeValidationError = {
                  /**
                  * Indicates that the error occurred because all alternatives (e.g. in `oneOf()`) were invalid
                  */
                  type: 'alternative';
                  /**
                  * The error message
                  */
                  msg: any;
                  /**
                  * The list of underlying validation errors returned by validation chains in `oneOf()`
                  */
                  nestedErrors: FieldValidationError[];
                  };

                    type CustomSanitizer

                    type CustomSanitizer = (input: any, meta: Meta) => any;

                      type CustomSchema

                      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;
                      • Mapping from field name to a validations/sanitizations schema, including extensions from an ExpressValidator instance.

                      type CustomValidationChain

                      type CustomValidationChain<T extends ExpressValidator<any, any, any>> =
                      T extends ExpressValidator<infer V, infer S, any>
                      ? ValidationChainWithExtensions<Extract<keyof V | keyof S, string>>
                      : never;
                      • Type of a validation chain created by a custom ExpressValidator instance.

                        Example 1

                        const myExpressValidator = new ExpressValidator({
                        isAllowedDomain: value => value.endsWith('@gmail.com')
                        });
                        type MyCustomValidationChain = CustomValidationChain<typeof myExpressValidator>
                        function createMyCustomChain(): MyCustomValidationChain {
                        return myExpressValidator.body('email').isAllowedDomain();
                        }

                      type CustomValidator

                      type CustomValidator = (input: any, meta: Meta) => any;
                      • A function which may - return falsy values, a promise that rejects or throw to indicate that a field is invalid; - return truthy values or a promise that resolves to indicate that a field is valid.

                        Parameter input

                        the field value

                        Parameter meta

                        metadata about the field being validated

                      type ErrorFormatter

                      type ErrorFormatter<T = any> = (error: ValidationError) => T;
                      • Given a validation error, returns a new value that represents it.

                      type FieldMessageFactory

                      type FieldMessageFactory = (value: any, meta: Meta) => any;
                      • A function which creates an error message based on a field's value.

                        Parameter input

                        the field value

                        Parameter meta

                        metadata about the field that was validated

                      type FieldValidationError

                      type FieldValidationError = {
                      /**
                      * Indicates that the error occurred because a field had an invalid value
                      */
                      type: 'field';
                      /**
                      * The location within the request where this field is
                      */
                      location: Location;
                      /**
                      * The path to the field which has a validation error
                      */
                      path: string;
                      /**
                      * The value of the field
                      */
                      value: any;
                      /**
                      * The error message
                      */
                      msg: any;
                      };

                        type GroupedAlternativeMessageFactory

                        type GroupedAlternativeMessageFactory = (
                        nestedErrors: FieldValidationError[][],
                        opts: {
                        req: Request;
                        }
                        ) => any;
                        • A function which creates an error message based on a group of alternatives nested errors.

                          Parameter nestedErrors

                          The errors from the invalid alternative groups.

                          Parameter opts

                          See Also

                          • oneOf()

                        type GroupedAlternativeValidationError

                        type GroupedAlternativeValidationError = {
                        /**
                        * Indicates that the error occurred because all alternatives (e.g. in `oneOf()`) were invalid,
                        * and the nested errors are grouped per alternative.
                        */
                        type: 'alternative_grouped';
                        /**
                        * The error message
                        */
                        msg: any;
                        /**
                        * The list of underlying validation errors returned by validation chains in `oneOf()`
                        */
                        nestedErrors: FieldValidationError[][];
                        };

                          type Location

                          type Location = 'body' | 'cookies' | 'headers' | 'params' | 'query';

                            type MatchedDataOptions

                            type MatchedDataOptions = {
                            /**
                            * Whether the value returned by `matchedData()` should include data deemed optional.
                            * @default false
                            */
                            includeOptionals: boolean;
                            /**
                            * An array of locations in the request to extract the data from.
                            */
                            locations: Location[];
                            /**
                            * Whether the value returned by `matchedData()` should include only values that have passed
                            * validation.
                            * @default true
                            */
                            onlyValidData: boolean;
                            };

                              type Meta

                              type Meta = {
                              /**
                              * The express request from which the field was validated
                              */
                              req: Request;
                              /**
                              * Which of the request objects the field was picked from
                              */
                              location: Location;
                              /**
                              * The full path of the field within the request object.
                              *
                              * @example
                              * const meta = { req, location: 'body', path: 'foo.bar' }; // req.body.foo.bar
                              */
                              path: string;
                              };
                              • Metadata about a validated field.

                              type OneOfErrorType

                              type OneOfErrorType = 'grouped' | 'least_errored' | 'flat';

                                type OneOfOptions

                                type OneOfOptions =
                                | {
                                /**
                                * The error message to use in case none of the chains are valid.
                                */
                                message?: AlternativeMessageFactory | ErrorMessage;
                                errorType?: Exclude<OneOfErrorType, 'grouped'>;
                                }
                                | {
                                /**
                                * The error message to use in case none of the chain groups are valid.
                                */
                                message?: GroupedAlternativeMessageFactory | ErrorMessage;
                                errorType?: 'grouped';
                                };

                                  type ParamSchema

                                  type ParamSchema<T extends string = DefaultSchemaKeys> = BaseParamSchema &
                                  ValidatorsSchema &
                                  SanitizersSchema & {
                                  [K in T]?: K extends keyof BaseParamSchema
                                  ? BaseParamSchema[K]
                                  : K extends keyof ValidatorsSchema
                                  ? ValidatorsSchema[K]
                                  : K extends keyof SanitizersSchema
                                  ? SanitizersSchema[K]
                                  : CustomValidatorSchemaOptions | CustomSanitizerSchemaOptions;
                                  };
                                  • Defines a schema of validations/sanitizations for a field

                                  type ParamSchemaWithExtensions

                                  type ParamSchemaWithExtensions<
                                  V extends string,
                                  S extends string,
                                  T extends string = DefaultSchemaKeys
                                  > = {
                                  [K in keyof ParamSchema<T> | V | S]?: K extends V
                                  ? ExtensionValidatorSchemaOptions
                                  : K extends S
                                  ? ExtensionSanitizerSchemaOptions
                                  : K extends keyof ParamSchema<T>
                                  ? ParamSchema<T>[K]
                                  : never;
                                  };
                                  • Schema of validations/sanitizations for a field, including extension validators/sanitizers

                                  type ResultFactory

                                  type ResultFactory<T> = (req: Request) => Result<T>;

                                    type Schema

                                    type Schema<T extends string = DefaultSchemaKeys> = Record<string, ParamSchema<T>>;
                                    • Defines a mapping from field name to a validations/sanitizations schema.

                                    type UnknownFieldMessageFactory

                                    type UnknownFieldMessageFactory = (
                                    unknownFields: UnknownFieldInstance[],
                                    opts: {
                                    req: Request;
                                    }
                                    ) => any;
                                    • A function which creates an error message based on unknown fields.

                                      Parameter unknownFields

                                      The unknown fields found in the request

                                      Parameter opts

                                      See Also

                                      • checkExact()

                                    type UnknownFieldsError

                                    type UnknownFieldsError = {
                                    /**
                                    * Indicates that the error occurred because one or more fields are unknown in the request
                                    */
                                    type: 'unknown_fields';
                                    /**
                                    * The error message
                                    */
                                    msg: any;
                                    /**
                                    * The list of fields that are unknown
                                    */
                                    fields: UnknownFieldInstance[];
                                    };

                                      type ValidationChainWithExtensions

                                      type ValidationChainWithExtensions<T extends string> = Middleware & {
                                      [K in keyof ValidationChain]: ValidationChain[K] extends (
                                      ...args: infer A
                                      ) => ValidationChain
                                      ? (...params: A) => ValidationChainWithExtensions<T>
                                      : ValidationChain[K];
                                      } & {
                                      [K in T]: () => ValidationChainWithExtensions<T>;
                                      };
                                      • A validation chain that contains some extension validators/sanitizers.

                                        Built-in methods return the same chain type so that chaining using more of the extensions is possible.

                                        Example 1

                                        function createChain(chain: ValidationChainWithExtensions<'isAllowedDomain' | 'removeEmailAttribute'>) {
                                        return chain
                                        .isEmail()
                                        .isAllowedDomain()
                                        .trim()
                                        .removeEmailAttribute();
                                        }

                                      type ValidationError

                                      type ValidationError =
                                      | AlternativeValidationError
                                      | GroupedAlternativeValidationError
                                      | UnknownFieldsError
                                      | FieldValidationError;
                                      • A validation error as reported by a middleware. The properties available in the error object vary according to the type.

                                        Example 1

                                        if (error.type === 'alternative') { console.log(There are ${error.nestedErrors.length} errors under this alternative list); } else if (error.type === 'field') { console.log(There's an error with field ${error.path} in the request ${error.location}); }

                                      Package Files (11)

                                      Dependencies (2)

                                      Dev Dependencies (15)

                                      Peer Dependencies (0)

                                      No peer dependencies.

                                      Badge

                                      To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                      You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/express-validator.

                                      • Markdown
                                        [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/express-validator)
                                      • HTML
                                        <a href="https://www.jsdocs.io/package/express-validator"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>