我使用@hapi/joi进行快速验证和卫生处理。验证时,某些验证器不起作用。在这个例子中,trim((不仅不会验证输入字符串开头和结尾的空白,而且也不会按照假设的方式对其进行修剪,因为默认情况下convert设置为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"
})
});
使用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' }
尝试将trim((与strict((一起使用
const Joi = require("@hapi/joi");
const string = Joi.string();
const localRegistrationSchema = Joi.object().keys({
email: string
.email()
.trim()
.strict()
.required()
});