express-validator 定制完全指南:自定义校验器、自定义清洗器、错误消息与 ExpressValidator 类

原创2026-10-09 14:46:071,437 阅读
文章标签:后端

express-validator 定制完全指南:自定义校验器、自定义清洗器、错误消息与 ExpressValidator 类

express-validator 内置了大量基于 validator.js 的校验器与清洗器,但真实业务中你迟早会遇到"内置能力覆盖不到"的场景:例如校验邮箱是否已被注册、把字符串 ID 转成 MongoDB ObjectId、屏蔽敏感词、为不同校验器输出不同的错误消息。本文围绕官方定制指南《Customizing express-validator》,系统讲解三条定制路径——自定义校验器/清洗器(.custom() / .customSanitizer())、多级错误消息定制(.withMessage()、抛错值、字段级消息)、ExpressValidator 类整体复用定制能力,并结合本仓库源码逐层剖析其底层执行逻辑,读完你即可在真实 Express 应用中落地一套完整的定制校验方案。

为什么需要定制

官方文档开门见山:只要应用稍微复杂一点,内置的校验器、清洗器和错误消息就不够用了。一个典型例子是注册场景下的邮箱唯一性校验——内置的 isEmail() 只能判断"格式是否合法",无法回答"这个邮箱是否已被占用",因为后者需要访问数据库,属于业务逻辑,只能由开发者自己实现。

express-validator 为此提供了多种定制入口,全部围绕三个核心概念展开:

  1. 自定义校验器:一个函数,接收字段值和元信息,返回值决定字段是否合法;
  2. 自定义清洗器:一个函数,接收字段值并返回一个新值,直接改写字段;
  3. 错误消息:默认的 Invalid value 太笼统,需要按校验器、按字段粒度定制更可读的消息。

下面逐一展开,每一部分都结合源码说明"它到底是怎么执行的"。

自定义校验器:.custom()

判定规则

自定义校验器的判定规则只有三条(关联文档):

  • 返回真值(truthy) → 字段有效;
  • 返回假值(falsy) → 字段无效;
  • 返回 Promise → 会等待其 settle:resolve 即视为有效(无论 resolve 的值是真还是假),reject 视为无效;
  • 抛出异常(throw) → 字段无效。

底层执行逻辑

这些规则并非文档的"口头约定",而是 CustomValidation 这个 ContextItem 的硬编码行为。查看 src/context-items/custom-validation.ts 的实现:

async run(context: Context, value: any, meta: Meta) {
  try {
    const result = this.validator(value, meta);
    const actualResult = await result;
    const isPromise = result?.then;
    const failed = this.negated ? actualResult : !actualResult;

    // A promise that was resolved only adds an error if negated.
    // Otherwise it always succeeds
    if ((!isPromise && failed) || (isPromise && this.negated)) {
      context.addError({ type: 'field', message: this.message, value, meta });
    }
  } catch (err) {
    if (this.negated) {
      return;
    }
    context.addError({
      type: 'field',
      message: this.message || (err instanceof Error ? err.message : err),
      value,
      meta,
    });
  }
}

从源码可以精确对应上文规则:

  • await result 统一 await,所以同步函数和异步函数都能处理;
  • 对非 Promise 返回值,!actualResult 为真即记录错误(假值无效);
  • 对 Promise,只要 resolve 就不记错("it must resolve in order for the field to be valid"),只有配合 .not() 取反(negated)时才在 resolve 后记错;
  • 抛错被 catch 捕获后记入错误,且抛出的 Error 的 message 会被当作错误消息(后面"错误消息"一节还会用到这一点)。

示例一:校验邮箱未被注册

app.post(
  '/create-user',
  body('email').custom(async value => {
    const user = await UserCollection.findUserByEmail(value);
    if (user) {
      throw new Error('E-mail already in use');
    }
  }),
  (req, res) => {
    // Handle the request
  },
);

这个例子同时演示了 .custom() 的三个典型用法:异步、访问数据库、通过抛错同时完成"判定无效"和"携带错误消息"两件事。

示例二:校验两次密码输入一致

app.post(
  '/create-user',
  body('password').isLength({ min: 5 }),
  body('passwordConfirmation').custom((value, { req }) => {
    return value === req.body.password;
  }),
  (req, res) => {
    // Handle request
  },
);

这里用到了自定义校验器接收的第二个参数 meta。它的完整类型定义在 src/base.ts:

export type Meta = {
  req: Request;                    // 当前 Express 请求对象
  location: Location;              // 字段来源:body/cookies/headers/params/query
  path: string;                    // 字段在请求对象中的完整路径,如 'foo.bar'
  pathValues: readonly (string | string[])[];
  // 通配符/globstar 选中字段时匹配到的值,例如 body('products.*.price')
};

因此 { req } 解构即可拿到整个请求对象,实现"一个字段的校验依赖另一个字段"这类跨字段逻辑。如果你用 body('products.*.quantity') 这类通配符选择字段,还可以通过 pathValues 拿到通配符实际匹配到的索引/键,结合 req 读取同一层级下的其他属性(详见字段选择指南)。

自定义清洗器:.customSanitizer()

判定规则

自定义清洗器规则更少:它返回什么,字段值就变成什么。同样支持异步——返回 Promise 时会被 await,resolve 出的值写入字段。唯一的"坑"在文档的警示框里:如果清洗器不写 return,字段会变成 undefined!

底层执行逻辑

src/context-items/sanitization.ts 中自定义清洗器的执行路径非常直观:

const runCustomSanitizer = async () => {
  const sanitizerValue = this.sanitizer(value, meta);
  return Promise.resolve(sanitizerValue);
};

if (this.custom) {
  const newValue = await runCustomSanitizer();
  context.setData(path, newValue, location);
  return;
}

Promise.resolve(sanitizerValue) 让同步/异步函数统一走 await,随后 context.setData(path, newValue, location) 把返回值写回字段——newValue 是 undefined 时自然就把字段置为 undefined,这正是文档警示的由来。对比之下,内置清洗器(如 trim、toLowerCase)会先经 stringify 转成字符串再执行,而自定义清洗器则原样接收任意类型(数组、对象、数字都可以),这也是它灵活的地方。

示例:把字符串 ID 转为 MongoDB ObjectId

import { param } from 'express-validator';
import { ObjectId } from 'mongodb';

app.post(
  '/user/:id',
  param('id').customSanitizer(value => ObjectId(value)),
  (req, res) => {
    // req.params.id is an ObjectId now
  },
);

清洗器在链路中的位置很关键:它发生在校验之前或之后取决于你把它放在链的哪个位置。放在最前面先转换类型,后续的 .isMongoId() 等校验器就能基于转换后的值工作;放在最后则只影响路由处理器里拿到的最终值。文档里还给出了一个更贴近真实场景的变体:根据 req.query.type 决定转成 ObjectId 还是 Number,演示了 meta.req 在清洗器中的跨字段作用(见 docs/api/validation-chain.md 的示例)。

错误消息定制:从默认 Invalid value 到逐级覆盖

每当字段校验失败,express-validator 都会为它记录一条错误消息。默认消息是 Invalid value(ExpressValidator.check 的 JSDoc 中标注为默认值),几乎不含任何业务信息,因此文档给出了四级定制手段,优先级从高到低排列如下。

校验器级消息:.withMessage()

只作用于紧邻的前一个校验器,通过 .withMessage() 指定(docs/api/validation-chain.md):

body('email').isEmail().withMessage('Not a valid e-mail address');

也就是说,链上不同的校验器可以各自携带不同的消息:

body('email')
  .isEmail().withMessage('Not a valid e-mail address')
  .custom(checkEmailNotInUse).withMessage('E-mail already in use');

自定义校验器级消息:抛出的值即消息

如果你在 .custom() 里 throw new Error(...),抛出值会被直接用作该字段的错误消息:

body('email')
  .isEmail()
  .custom(async value => {
    const existingUser = await Users.findByEmail(value);
    if (existingUser) {
      // Will use the below as the error message
      throw new Error('A user already exists with this e-mail address');
    }
  });

这正是 custom-validation.ts 中 message: this.message || (err instanceof Error ? err.message : err) 这行代码的体现:抛出的 Error 取 .message,抛出其他值则原样使用。

文档特别用 :::note 强调了一条优先级规则:.withMessage() 显式指定的消息优先于自定义校验器抛出的值。对照源码,this.message 就是 .withMessage() 在链上设置的消息,代码中它排在 || 的前面,优先级更高,与文档完全一致。

字段级消息:创建链时的兜底

在创建校验链时,body(fields, message) / check(fields, message) 的第二个参数就是字段级消息,作为链上某个校验器没有指定消息时的兜底:

body('json_string', 'Invalid json_string')
  // No message specified for isJSON, so use the default "Invalid json_string"
  .isJSON()
  .isLength({ max: 100 })
  // Overrides the default message when `isLength` fails
  .withMessage('Max length is 100 bytes');

执行顺序是:字段级消息 → 校验器未覆盖时生效;一旦某个校验器用了 .withMessage(),该校验器的失败消息就被后者覆盖。字段级消息在底层由 ContextBuilder.setMessage() 写入 Context(src/context-builder.ts),并在 check() 创建链时传入(src/middlewares/check.ts)。

特殊函数的错误消息:checkExact() 与 oneOf()

文档提醒,部分 express-validator 函数会产生不同类型的错误,因此消息定制方式也不同:

  • checkExact():校验请求中是否出现未被声明验证的字段,其"多余字段"错误(type: 'fields_limit')需要用它自己的消息配置;
  • oneOf():要求一组链中至少一个通过,失败时产生 type: 'alternative' 的错误,nestedErrors 下携带每条链的明细,错误消息需要在其选项里配置。

这两类错误不属于 type: 'field',阅读各自 API 文档即可看到完整的选项说明。

ExpressValidator 类:把整套定制固化成可复用实例

为什么需要它

如果你在几十个路由里都要用 isEmailNotInUse 这类自定义校验器,每个链都写一遍 body('x').custom(checkEmailNotInUse) 显然很啰嗦,而且无法利用 schema 形式声明。ExpressValidator 类就是为此设计的:它把 express-validator 的全部 API(body、param、checkSchema、matchedData、oneOf、validationResult 等)连同你注入的定制,打包成一个实例。

构造参数

src/express-validator.ts 定义了构造函数签名:

constructor(
  validators?: Record<string, CustomValidator>,   // 自定义校验器集合
  sanitizers?: Record<string, CustomSanitizer>,   // 自定义清洗器集合
  options?: { errorFormatter?: ErrorFormatter<E> } // 实例级默认错误格式化器
)

三个参数分别对应三类定制:自定义校验器、自定义清洗器、默认错误格式化器(后者的完整说明见 docs/api/validation-result.md#errorformatter)。

底层如何"注入"定制

createChain()(src/express-validator.ts)揭示了实现原理:实例在创建每条校验链时,会把注册的每个校验器包装成 () => middleware.custom(fn)、把每个清洗器包装成 () => middleware.customSanitizer(fn),然后 Object.assign 到 middleware 上。这意味着:

  • 注入的校验器/清洗器只对来自该实例的链可用(body('x').isPostID());
  • 实例的 checkSchema 会把这些扩展名校验器/清洗器同时接入 schema 解析(src/middlewares/schema.ts 中 createCheckSchema 的 extraValidators / extraSanitizers 参数),因此 schema 里可以直接写 { isEmailNotInUse: true }。

validationResult 的定制则通过 result.formatWith() 实现:实例化时传入的 errorFormatter 会在取结果时自动套用(src/express-validator.ts)。

完整示例

import { ExpressValidator } from 'express-validator';

const { body, param, validationResult } = new ExpressValidator(
  {
    isPostID: async value => {
      // Verify if the value matches the post ID format
    },
  },
  {
    muteOffensiveWords: value => {
      // Replace offensive words with ***
    },
  },
);

app.post(
  '/forum/:post/comment',
  param('post').isPostID(),
  body('comment').muteOffensiveWords(),
  (req, res) => {
    const result = validationResult(req);
    // Handle new post validation result
  },
);

isPostID 和 muteOffensiveWords 使用起来与内置方法毫无区别,可以随意与内置方法混排在同一链路中。再配合第三个参数,可以同时定制默认错误格式化器:

const { query, validationResult } = new ExpressValidator({}, {}, {
  errorFormatter: error => error.msg,
});

app.post('/hello', query('person').notEmpty(), (req, res) => {
  const errors = validationResult(req).array();
  // => ['Invalid value', ... ]
});

这里 validationResult(req).array() 输出的就是格式化后的字符串数组,而不是默认的完整错误对象;如果某次需要临时换一种格式,仍可通过 result.formatWith(...) 覆盖(示例见 docs/api/express-validator.md)。

ExpressValidator 还提供 check、cookie、header、query、checkExact、matchedData、oneOf 等成员(src/express-validator.ts),覆盖了从顶层导入的绝大部分 API,意味着你可以完全不依赖顶层导出、只用实例完成整套校验与结果提取。完整 API 清单见 docs/api/express-validator.md。

TypeScript 支持:CustomValidationChain 与 CustomSchema

实例化的定制在 TypeScript 下同样有类型保障。通过两个导出类型,可以拿到与实例类型精确匹配的链类型和 schema 类型:

import { ExpressValidator, CustomValidationChain, CustomSchema } from 'express-validator';

const myExpressValidator = new ExpressValidator({ isEmailNotInUse });
const { body, checkSchema } = myExpressValidator;

type MyValidationChain = CustomValidationChain<typeof myExpressValidator>;
type MySchema = CustomSchema<typeof myExpressValidator>;

const createEmailChain = (): MyValidationChain => body('email').isEmail().isEmailNotInUse();
const signupSchema: MySchema = {
  email: {
    isEmail: true,
    isEmailNotInUse: true,
  },
};

CustomValidationChain<typeof instance> 会在链类型上额外声明实例注册过的扩展方法名(即 ValidationChainWithExtensions<T>,见 src/express-validator.ts),所以 createEmailChain 里 .isEmailNotInUse() 能被类型系统识别并校验;CustomSchema<typeof instance> 则让 schema 对象可以使用同样的扩展键(src/express-validator.ts)。配合 checkSchema 的 RunnableValidationChains 返回类型(src/middlewares/schema.ts),甚至可以在不挂载为中间件的情况下手动 schema.run(req) 并拿到结构化结果。

此外,实例泛型本身也携带定制信息:ExpressValidator<V, S, E> 的三个类型参数分别对应自定义校验器表、自定义清洗器表和错误类型,这让 .validationResult() 的返回结果 Result<E> 也能享受类型层面的定制(docs/api/express-validator.md)。

小结

围绕定制这一主题,express-validator 提供了三条层层递进的能力:

  1. 单次定制:.custom() 与 .customSanitizer() 解决"内置没有的函数",meta 参数(req、location、path、pathValues)让你能访问请求上下文与通配符匹配信息,底层由 custom-validation.ts 和 sanitization.ts 保证同步/异步、抛错/返回语义的一致性;
  2. 消息定制:从默认 Invalid value 出发,.withMessage()(校验器级)、抛错值(自定义校验器级,且 .withMessage() 优先级更高)、字段级兜底消息三层覆盖,checkExact() / oneOf() 则用各自独立的错误类型与消息配置;
  3. 整体复用:ExpressValidator 类把自定义校验器、清洗器和默认错误格式化器固化进一个实例,产出 body / param / checkSchema / validationResult 等一整套可用 API,并通过 CustomValidationChain / CustomSchema 两个类型让定制在 TypeScript 下保持完整类型安全。

本文涉及的其余 API 细节可继续阅读仓库内对应文档:校验链完整 API、ExpressValidator 类 API、错误结果与格式化 以及字段选择指南。

登录后查看全文
express-validator