Node The Js Express Validator field is required only if the other has a specific value.

I use express validator to check message fields. My problem is that I want some fields to be needed only if other fields have certain values. eg:

if person_organisation is true: person_organisation_name must be required if person_organisation is false: person_first_name must be required 

Is there any way to put these rules into the validation scheme ??

+5
source share
1 answer

Create your own check:

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

and use:

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

Source: https://habr.com/ru/post/1267069/


All Articles