我想让Joi拒绝像"或"这样的字符串,我该如何实现?
使用trim
和min
:
const schema = Joi
.string()
.trim()
.min(1)
.required();
测试:
console.log(schema.validate(' ')); // "value" is not allowed to be empty
console.log(schema.validate('')); // "value" is not allowed to be empty
console.log(schema.validate(' foo')); // value: 'foo'
console.log(schema.validate('foo ')); // value: 'foo'
用例
有一个验证csv文件的案例(通过Papa Parse(,并要求Joi无法通过trim()
验证。trim()
的正常行为是修复空白,这是合理的。
我们希望通过trim()
出现验证错误,而不是自动修复。
示例
默认
RESULT:没有详细错误/通过验证/修剪空白
const schema1 = Joi.object({ username: Joi.string().trim() })
const hasValidationError1 = schema1.validate({ username: ' aslezak ' })
// hasValidationError1 { value: { username: 'aslezak' } }
覆盖
RESULT:显式详细错误/验证失败/需要在csv中修复修剪并重新处理
const schema2 = Joi.object({ username: Joi.string().trim() })
const hasValidationError2 = schema2.validate(
{ username: ' aslezak ' },
{ abortEarly: false, convert: false, label: ['path', 'key', true] }
)
// hasValidationError2 = {
// value: { username: ' aslezak ' },
// error: { ValidationError: [ `"username" must not have leading or trailing whitespace.` ] },
// }
在joi.dev文档中引用validate()
方法有助于确定配置选项。
API文档
https://joi.dev/api/?v=17.4.0#anyvalidatevalue-选项
此处的其他答案包括不相关的详细信息,因此需要回复。
Joi的默认设置只需要在validate()
调用中添加convert: false
。不需要修剪,不需要提前中止或任何其他事情。
const result = Joi.validate("foo@example.com ", Joi.string().email(), {
convert: false
});
结果:
{
"error": {
"isJoi": true,
"name": "ValidationError",
"details": [
{
"message": ""value" must be a valid email",
"path": [],
"type": "string.email",
"context": {
"value": "foo@example.com ",
"label": "value"
}
}
],
"_object": "foo@example.com "
},
"value": "foo@example.com "
}
如果您想防止空字符串
Joi.string().required().min(1)