Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
Node Js Express Validator required field only if another have a specific value

I use express-validator to check my post fields. My Problem is I want to make some fields required only if other fields have a specific 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 this rules in Validation Schema??

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Create custom validation:

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
  });
});
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!