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

396
Views
Node Js Express validator Check if field is numeric only if it is not empty

I use express-validator to check my post fields, one of my field must be a decimal or empty. I used this Schema:

request.checkBody({ 
        'product_price': {
            optional: true,
            isDecimal: {
                errorMessage: 'The product price must be a decimal'
            }
        }
})

The problem with this Schema is to not validate my post if product_price is empty, even with "optional: true".

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You need to set the checkFalsy option for optional to allow defined-but-empty values:

request.checkBody({ 
  'product_price': {
    optional: {
      options: { checkFalsy: true }
    },
    isDecimal: {
      errorMessage: 'The product price must be a decimal'
    }
  }
});

EDIT: the documentation has been moved since posting this answer, it can now be found here.

about 4 years ago · Santiago Trujillo Report

0

What worked for me was using req.checkBody('optionalParam', 'optionalParam must be a number').optional().isNumber();

about 4 years ago · Santiago Trujillo Report

0

In case if someone is using express-validator body. You can do the following thing

router.post('apiname', [
  body('product_price').trim()
    .optional({ checkFalsy: true })
    .isNumeric().withMessage('Only Decimals allowed'),
])
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!