【问题标题】:Node Js Express Validator required field only if another have a specific value仅当另一个具有特定值时,Node Js Express Validator 才需要字段
【发布时间】:2017-09-20 05:12:32
【问题描述】:

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

if person_organisation is true:
person_organisation_name must be required

if person_organisation is false:
person_first_name must be required

有没有办法把这个规则放到验证模式中??

【问题讨论】:

    标签: javascript node.js validation express


    【解决方案1】:

    创建自定义验证:

    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
      });
    });
    

    【讨论】:

    • 正是我需要的,谢谢。
    • 乐于助人 (:
    猜你喜欢
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 2013-08-06
    • 2012-02-09
    • 2018-12-29
    • 2019-03-18
    • 1970-01-01
    • 2017-11-22
    相关资源
    最近更新 更多