【问题标题】:Joi validation string().trim() not workingJoi 验证 string().trim() 不工作
【发布时间】:2020-07-16 06:08:18
【问题描述】:

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

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"
    })
});

【问题讨论】:

    标签: express validation hapijs joi


    【解决方案1】:

    如果 Joi 的版本 >= 17,您可以编写如下架构:

    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' }
    

    【讨论】:

    • 是的,这段代码和我的原始代码都适用于控制台日志。我正在使用邮递员进行测试。会不会是邮递员发送表单数据的方式?我正在使用 x-www-form-urlencoded 发送要验证的表单数据。
    • 你能添加一个一致的 curl 命令吗?也许我可以测试一下。
    • curl --location --request POST 'localhost:5000/api/auth/register/local' \ --header 'Content-Type: application/x-www-form-urlencoded' \ - -header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode 'email= foo@bar.com ' \ --data-urlencode 'password=password' \ --data-urlencode ' confirmPassword=password'\--data-urlencode'username=foobar'
    • 没关系。我将原始正文传递给我的数据库,而不是经过验证和清理的值。而且我没有收到我期望的错误,因为它正在清理它们,因此清理后的值没有错误。
    • 好吧,听起来很合理。什么工作通常都很好:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多