Joi 如何验证字段应该为空
Joi how to validate a field should be empty
当角色为 "student" 时,需要 parentemail
。否则它应该是空的。
当我提供 parentemail
时,以下内容不起作用。
如何验证字段是否为空,如果不为空,则会发生错误。
parentemail: Joi.string().email().when("role", {
is: "student",
then: Joi.required(),
otherwise: Joi.empty(undefined)
}),
我不确定您对 Joi.empty()
的使用是否正确。文档说:
any.empty(schema)
Considers anything that matches the schema to be empty (undefined).
这表明应该使用它来扩展 Joi 对 'empty' 定义的看法。
改为尝试类似的方法:
Joi.object().keys({
role: Joi.string(),
parentemail: Joi.when('role', {
is: 'student',
then: Joi.string().email().required(),
otherwise: Joi.string().valid([ null, '' ])
})
})
当 role
是 'student'
.
或者,当 role
为 'student'
时,您可以通过将 otherwise
更改为
来完全禁止 parentemail
otherwise: Joi.forbidden()
当角色为 "student" 时,需要 parentemail
。否则它应该是空的。
当我提供 parentemail
时,以下内容不起作用。
如何验证字段是否为空,如果不为空,则会发生错误。
parentemail: Joi.string().email().when("role", {
is: "student",
then: Joi.required(),
otherwise: Joi.empty(undefined)
}),
我不确定您对 Joi.empty()
的使用是否正确。文档说:
any.empty(schema)
Considers anything that matches the schema to be empty (undefined).
这表明应该使用它来扩展 Joi 对 'empty' 定义的看法。
改为尝试类似的方法:
Joi.object().keys({
role: Joi.string(),
parentemail: Joi.when('role', {
is: 'student',
then: Joi.string().email().required(),
otherwise: Joi.string().valid([ null, '' ])
})
})
当 role
是 'student'
.
或者,当 role
为 'student'
时,您可以通过将 otherwise
更改为
parentemail
otherwise: Joi.forbidden()