nodejs condense a validation of json body request against regex

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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
    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x