Joi验证:用户名不能为电子邮件地址

问题描述 投票:0回答:1

否定Joi的内置email()验证程序有什么方法?

类似于此伪代码:

username: Joi.string().not.Joi.email()

OR

username: Joi.string().Joi.email().invert()

我能够使其与以下Regex一起使用:

const emailRegEx = RegExp('^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$');
const schema2 = Joi.object({
     username: Joi.string().regex(emailRegEx, { invert: true })
 })
javascript validation joi
1个回答
0
投票

不确定这是否是最好的方法,但是您可以尝试以下方法:

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: '[email protected]' }); // error: Error: must not be an email
© www.soinside.com 2019 - 2024. All rights reserved.