Joi 验证字符串().trim() 不起作用

Joe*_*sen 2 validation express hapijs joi

我正在使用 @hapi/joi 进行快速验证和卫生。验证时,某些验证器不工作。在这个中,trim() 不仅不会验证输入字符串开头和结尾的空格,而且它也不会修剪它,因为它应该默认将 convert 设置为 true。但是,检查有效电子邮件和需要两者都可以工作并抛出各自的错误。我也试过小写(),但没有验证或将其转换为小写。

const Joi = require("@hapi/joi");

const string = Joi.string();

const localRegistrationSchema = Joi.object().keys({
  email: string
    .email()
    .trim()
    .required()
    .messages({
      "string.email": "Email must be a valid email address",
      "string.trim": "Email may not contain any spaces at the beginning or end",
      "string.empty": "Email is required"
    })
});
Run Code Online (Sandbox Code Playgroud)

pza*_*ger 5

使用版本 >= 17 的 Joi,您可以按如下方式编写架构:

const localRegistrationSchema = Joi.object({ // changes here,
  email: Joi.string() // here
    .email()
    .trim()
    .lowercase() // and here
    .required()
    .messages({
      'string.email': 'Email must be a valid email address',
      'string.trim': 'Email may not contain any spaces at the beginning or end', // seems to be unnecessary
      'string.empty': 'Email is required'
    })
});

console.log(localRegistrationSchema.validate({ email: '' }));
// error: [Error [ValidationError]: Email is required]

console.log(localRegistrationSchema.validate({ email: '  foo@bar.com' }));
// value: { email: 'foo@bar.com' }

console.log(localRegistrationSchema.validate({ email: 'foo@bar.com  ' }));
// value: { email: 'foo@bar.com' }

console.log(localRegistrationSchema.validate({ email: 'FOO@BAR.COM' }));
// value: { email: 'foo@bar.com' }
Run Code Online (Sandbox Code Playgroud)