2017-04-23 49 views
5

我使用express-validator來檢查我的帖子字段。我的問題是我想只有在其他字段具有特定值時才需要一些字段。 如:只有當另一個具有特定值時,才需要Js Express Validator字段

if person_organisation is true: 
person_organisation_name must be required 

if person_organisation is false: 
person_first_name must be required 

有什麼辦法可以把在驗證架構這個規則?

回答

4

創建自定義的驗證:

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

正是我需要的,謝謝。 – medKHELIFI

+0

很樂於幫助(: – num8er

相關問題