Home > Enterprise >  nodejs condense a validation of json body request against regex
nodejs condense a validation of json body request against regex

Time:03-08

Is there a condensed way to do this validation on nodejs

//inbound express request
{ "myVal":"abcdefghij" }

/* first test if value exists,
   then if it fails a regex return an error & exit function
   if pass then continue
*/
 // ... logic to get express.post(...=> {
     if ((  req.body.myVal == null ){
            // no value, send error response and exit function
          }else{
              const inVar = req.body.myVal;
              if ( inVar ){
                    const regex = /^([a-j0-9]){1,11}$/;
                    if(regex.test(inVar ) == false){
                          res.send({ error: "failed regex" });  
                          res.end();
                          return;
                     }
               ...  else continue     



              
      
          

CodePudding user response:

Here are a few options:

  1. Use express-validator or a similar package to validate your endpoint params and/or body in the endpoint configuration. This nicely separates validation from the logic of the endpoint and is extensible to your other endpoints without having to maintain code in each one.

Check out the package here: Express-validator

Specifically, what you might want is their custom validator: Express-validator's custom validation docs

Example usage:

const { body } = require('express-validator');
const MY_REGEX = /^([a-j0-9]){1,11}$/;

app.post('/my-endpoint',
  body('myVar').custom(value => {
    if(!MY_REGEX.test(value)) Promise.reject("Error: invalid value for 'myVar.'")
  }),
  (req, res) => {
    // Business logic only, no validation
  },
);

You could even take the function that's inside .custom(), and put it in another file, import it here, and reuse it elsewhere.

  1. If you want to do the validation in the handler, there are a few ways to make your code more brief/safe/nice.
  • Set your regexp variable in a different file or as a constant at the top of the file (descriptively) or in a different constants/utils file.
  • "Error gate" by returning after you find an error. Avoid nested if/else.
  • Is the error the same for missing value and incorrect value? If so, your regexp will error appropriately for undefined, empty string, and null anyway. consider combining them in the same if statement. Example:
    // imports
    // ...
    const MY_DESCRIPTIVE_REGEX_NAME = /^([a-j0-9]){1,11}$/;
    //... 
    (req, res) => {
      if(!MY_DESCRIPTIVE_REGEX_NAME.test(req.body.myVal) {
        res.status(400);
        return res.send({ error: "MyVal must be between 1 and 11 characters and contain only numbers and letters between 'a' and 'j'."});
      }
      // rest of logic, not in an if statement
    }
  • Related