Javascript Joi验证:用户名不能是电子邮件地址
有没有办法通过否定Joi内置的email()验证器来做到这一点 类似这样的伪代码:Javascript Joi验证:用户名不能是电子邮件地址,javascript,validation,joi,Javascript,Validation,Joi,有没有办法通过否定Joi内置的email()验证器来做到这一点 类似这样的伪代码: username: Joi.string().not.Joi.email() 或 我能够使用以下正则表达式使其工作: const emailRegEx = RegExp('^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$'); const schema2 = Joi.object({ username: Joi.string().regex(e
username: Joi.string().not.Joi.email()
或
我能够使用以下正则表达式使其工作:
const emailRegEx = RegExp('^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$');
const schema2 = Joi.object({
username: Joi.string().regex(emailRegEx, { invert: true })
})
不确定这是否是最好的方法,但您可以尝试以下方法:
const schema = Joi.object().keys({
username: Joi.alternatives().when(
Joi.string().email(),
{
then: Joi.forbidden().error(new Error('must not be an email')),
otherwise: Joi.string().required()
}
)
});
schema.validate({ username: 'whatever' }); // error: null, value: { username: 'whatever' }
schema.validate({ username: 'my@email.com' }); // error: Error: must not be an email
const schema = Joi.object().keys({
username: Joi.alternatives().when(
Joi.string().email(),
{
then: Joi.forbidden().error(new Error('must not be an email')),
otherwise: Joi.string().required()
}
)
});
schema.validate({ username: 'whatever' }); // error: null, value: { username: 'whatever' }
schema.validate({ username: 'my@email.com' }); // error: Error: must not be an email