如何验证 ObjectID

How to validate for ObjectID

使用 Joi 模式验证,是否可以针对 MongoDB ObjectID 进行验证?

这样的东西可能很棒:

_id: Joi.ObjectId().required().error(errorParser),
const Joi = require('@hapi/joi')
Joi.objectId = require('joi-objectid')(Joi)
 
const schema = Joi.object({
  id: Joi.objectId(),
  name: Joi.string().max(100),
  date: Joi.date()
})

结帐https://www.npmjs.com/package/joi-objectid

如果您使用的是新版本的 Joi,则此包有效。

const Joi = require('joi-oid')

const schema = Joi.object({
  id: Joi.objectId(),
  name: Joi.string(),
  age: Joi.number().min(18),
})

包:https://www.npmjs.com/package/joi-oid

如果你想在不安装任何东西的情况下将上述库的 TypeScript 版本与 Express 集成:

import Joi from '@hapi/joi';
import { createValidator } from 'express-joi-validation';

export const JoiObjectId = (message = 'valid id') => Joi.string().regex(/^[0-9a-fA-F]{24}$/, message)

const validator = createValidator({
    passError: true,
});

const params = Joi.object({
    id: JoiObjectId().required(),
});

router.get<{ id: string }>(
    '/:id',
    validator.params(params),
    (req, res, next) => { 
       const { id } = req.params; // id has string type
       .... 
    }
);

我发现如果我这样做

Joi.object({
  id: Joi.string().hex().length(24)
})

无需安装任何外部库或使用 RegEx 即可工作

hex 确保字符串只包含十六进制字符,length 确保它是恰好 24 个字符的字符串