Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Joi验证:用户名不能是电子邮件地址_Javascript_Validation_Joi - Fatal编程技术网

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

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

有没有办法通过否定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(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