提问者:小点点

在mongoose中使用validator函数验证密码


我设置了自定义验证函数,如下所示

 password: {
    type: String,
    required: true,
    validate: {
      validator: function (v) {
        return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@#!%*?&])[A-Za-z\d$@$!%*?&]{8,32}/.test(v)
      },
      message: 'min 8 max 32 upper 1 lower 1 special 1 number 1',
    },

这是路由文件中的。save()函数

newAuth.save({ runValidators: true } )

但是,验证程序没有工作。如何在Mongoose中运行。save()的regex验证程序?


共1个答案

匿名用户

使用.save()时,不应使用runvalidators:true选项,因为它用于更新验证(请参阅https://mongoosejs.com/docs/validation.html#update-validators)。我试着复制这种行为,但它和我预期的一样:

try {
  const newAuth = new AuthModel({password: "shouldfail"})
  await newAuth.save();
} catch(err) {
  console.log(err);
}

这将记录:

 {
    name: ValidatorError: min 8 max 32 upper 1 lower 1 special 1 number 1
        at validate ...
      properties: [Object],
      kind: 'user defined',
      path: 'password',
      value: 'shouldfail',
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    }