javascript - 仅当另一个具有特定值时,Node Js Express Validator 才需要字段

标签 javascript node.js validation express

我使用 express-validator 检查我的帖子字段。我的问题是我只想在其他字段具有特定值时才需要某些字段。 例如:

if person_organisation is true:
person_organisation_name must be required

if person_organisation is false:
person_first_name must be required

有什么方法可以将此规则放入验证模式中??

最佳答案

创建自定义验证:

app.use(expressValidator({
 customValidators: {
    checkPersonName: function(name, isPerson) {
        return isPerson === true ? name != '' : true;
    },
    checkOrganisationName: function(name, isPerson) {
        return isPerson === false ? name != '' : true;
    }
 }
}));

并使用:

app.post('/registration', function(req, res) {

  req.checkBody(
    'person_first_name', 'Please provide Your first name'
  ).checkPersonName(req.body.person_organisation);

  req.checkBody(
    'person_organisation_name', 'Please provide valid organisation name'
  ).checkOrganisationName(req.body.person_organisation);

  req.getValidationResult().then(function(result) {
    if (!result.isEmpty()) {
      res.status(400).send({result: result.array()});
      return;
    }

    res.json(); // when success do something
  });
});

关于javascript - 仅当另一个具有特定值时,Node Js Express Validator 才需要字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43572538/

相关文章:

javascript - django中破管错误的可疑解决方案

sql - 如何使用 SQL 查询在 Access 中的字段上设置验证规则?

javascript - 基于百分比的可能排列算法

javascript - 如何将文本框中的文本传递给 JavaScript 函数?

node.js - Firestore 实时更新 NodeJS 中的连接

node.js - 使用 sqlite3 进行 Sequelize 不会创建数据库

javascript - Node.js 中的 for 循环顺序错误(谷歌日历 api、mongojs)

javascript - jQuery 中的表单标签值

html - 了解错误 "Element legend not allowed as child of element div in this context."

javascript - 使用 google map js api v3 为路线制作动画