我有Express中内置的API。在“登录”中,我试图验证字段nickname
,它可能被用户名或电子邮件包含。
这是我的代码:
validate: function (method){
switch (method) {
case 'checkLogin': {
return [
oneOf([
check('nickname')
.exists()
.withMessage('nickname is required')
.isLength({ min: 5 })
.withMessage('username at least 5 characters'),
check('nickname')
.exists()
.withMessage('nickname is required')
.isEmail()
.withMessage('email not valid'),
]),
check('password')
.exists()
.withMessage('password is required')
]
}
}
},
上面的代码成功验证了昵称,但它返回了nestedErrors消息。
例如,如果我在字段昵称中输入john
,它将给我响应:
[
{
"code": 300,
"status": false,
"message": "Invalid value(s)",
"param": "_error",
"nestedErrors": [
{
"value": "kes",
"msg": "username at least 5 characters",
"param": "nickname",
"location": "body"
},
{
"value": "kes",
"msg": "email not valid",
"param": "nickname",
"location": "body"
}
]
}
]
如何根据输入类型做出响应。我的意思是,如果昵称不包含@
,则它不应该是电子邮件,因此只需返回用户名响应,如果昵称包含@
,则返回电子邮件响应。