node.js - nodejs 快速验证器 : validate email format only if value exists

标签 node.js express-validator

我有以下验证规则(nodejs、express-validator)

---------------------
check('email').not().isEmpty().withMessage('email is required'),
check('email').isEmail().withMessage('email not valid'),
---------------------

现在,如果我提交没有电子邮件地址值的表单,将会出现以下错误。

email is required 
email not valid

我只想在电子邮件值存在时检查电子邮件格式,这样只会出现一条错误消息,要么是“需要电子邮件”,要么是“电子邮件无效”。

有什么建议吗?

最佳答案

根据文档,.bail()如果链中的任何先前验证失败,可用于停止运行进一步的验证。

试试这个:

check("email")
  .not()
  .isEmpty()
  .withMessage("email is required")
  .bail()
  // if email is empty, the following will not be run
  .isEmail()
  .withMessage("email not valid");

关于node.js - nodejs 快速验证器 : validate email format only if value exists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66271788/

相关文章:

node.js - Express-validator 不会捕获错误

html - 如何使用 express-validator 验证字符的长度是否等于 5?

javascript - 我如何使用 Express-Validator 验证出生日期?

javascript - 如果请求体是单个 json 数组,如何验证请求体?

node.js - Angular-sails 中的 POST/GET 请求

node.js - 如何在不重新启动的情况下重新加载 Node-RED 中的 Node ?

javascript - 从 null 和 undefined 中清除对象

node.js - 如何找出 express 应用程序正在运行的当前 NODE_ENV?

node.js - Nodejs 错误没有回溯

express - 如果在Express-Validator中间件之前使用multer作为中间件功能,则存在Multer(Express)处理错误