javascript - 快速验证器如何仅在存在另一个字段时才需要该字段

标签 javascript node.js express express-validator

快速验证器,如何仅在存在另一个字段时才需要该字段?

const validateUpdateStore = () => {
  return [
    body('logo').optional().isURL().withMessage('invalid url'),
    body('email')
      .optional()
      .isEmail()
      .withMessage('email is invalid')
      .trim()
      .escape(),
    body('phone').optional().isInt().withMessage('integers only!'),
    body('account_number').optional().isInt().withMessage('integers only!'),
    body('bank_code').optional().isInt().withMessage('integers only!'),
  ];
};
我想做这个领域bank_code仅当 account_number 时需要提供,反之亦然

最佳答案

版本 6.1.0express-validator添加了对条件验证器的支持。我目前没有在文档中看到它,但有一个 pull request更多信息。看起来您应该能够如下定义您的验证:

const validateUpdateStore = () => {
  return [
    body('logo').optional().isURL().withMessage('invalid url'),
    body('email')
      .optional()
      .isEmail()
      .withMessage('email is invalid')
      .trim()
      .escape(),
    body('phone').optional().isInt().withMessage('integers only!'),
    body('account_number')
      .if(body('bank_code').exists()) // if bank code provided
      .not().empty() // then account number is also required
      .isInt() // along with the rest of the validation
      .withMessage('integers only!')
    ,
    body('bank_code')
      .if(body('account_number').exists()) // if account number provided
      .not().empty() // then bank code is also required
      .isInt() // along with the rest of the validation
      .withMessage('integers only!')
    ,
  ];
};

关于javascript - 快速验证器如何仅在存在另一个字段时才需要该字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64319368/

相关文章:

javascript - 如何将日期字符串解析为 dd/mm/yyyy?

javascript - 在 jQuery 中对页面上的所有更改进行实时操作?

Node.js https pem 错误 : error:0906D06C:PEM routines:PEM_read_bio:no start line

ruby-on-rails - 将带有 React 组件的 Ruby on Rails 项目部署到 Heroku

javascript - 将模板引擎加载到node.js/express中

javascript - 在 Html 中单击列表 (li) 项目不适用于 jquery

javascript - 文本在其他文本下方而不是旁边,尽管我没有使用任何奇怪的代码

memory - Node.js 在逐位读取大文件时内存不足

node.js - 使用布局时 Jade 模板引擎错误

node.js - 允许从特定移动应用程序调用 API