【问题标题】:Joi: "tel" is not allowed to be emptyJoi:“tel”不允许为空
【发布时间】:2018-01-12 21:11:19
【问题描述】:

即使tel 设置为可选,Joi 仍会返回以下错误。我们如何解决这个问题?

谢谢。

Error: Joi Failed: ValidationError: child "tel" failed because ["tel" is not allowed to be empty]


//Define Joi schema
const schema = {
    email: Joi.string().required().email({
        errorLevel: 64,
        minDomainAtoms: 2 
    }).min(6),
    tel: Joi.string().optional().min(10).max(10),
    password: Joi.string().required().min(8).max(64)
}

//Check inputs
const { error, value } = Joi.validate({ 
    email: args.email, 
    tel: tel, 
    password: args.password 
}, schema)   

【问题讨论】:

标签: javascript node.js validation joi


【解决方案1】:

...默认情况下不允许空字符串,必须使用 allow('')。但是,如果您想指定一个默认值以防万一 对于空字符串,您必须使用不同的模式: Joi.string().empty('').default('default value')。这告诉 Joi 空字符串应被视为空值(而不是 无效)以及使用哪个值作为默认值。

参考:Joi v10.6.0 Documetations

在你的情况下:

tel: Joi.string().optional().allow('').min(10).max(10)

【讨论】:

    猜你喜欢
    • 2019-06-01
    • 2021-07-06
    • 2022-11-12
    • 1970-01-01
    • 2017-05-19
    • 2017-07-11
    • 2020-02-19
    • 2019-08-08
    • 2015-10-04
    相关资源
    最近更新 更多