Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 408
medkhelifi Avatar asked Apr 23 '17 12:04

medkhelifi


People also ask

How do I validate a number in node JS?

You will need to convert the Buffer to String using toString() method. Once you have the String , you can try to parse the string to a number (Int or Float) using methods of Number class ( Number. parseInt or Number.

What is checkFalsy in Express validator?

What is checkFalsy in Express-validator? You can customize this behavior by passing an object with the following options: nullable: if true, fields with null values will be considered optional. checkFalsy: if true, fields with falsy values (eg "", 0, false, null) will also be considered optional.10-Jul-2014.

What is bail in Express validation?

According to the express-validator documentation: . bail() is useful to prevent a custom validator that touches a database or external API from running when you know it will fail. Can be used multiple times IN THE SAME validation chain if needed.13-Feb-2020.

How does express validator work?

According to the official website, Express Validator is a set of Express. js middleware that wraps validator. js , a library that provides validator and sanitizer functions. Simply said, Express Validator is an Express middleware library that you can incorporate in your apps for server-side data validation.


1 Answers

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.

like image 154
robertklep Avatar answered Nov 14 '22 23:11

robertklep