title: Express Validator, one function that will check multiple forms
body: <p>I have been attempting to use Express Validator, however I have come across a problem.</p>
  
  <p>Currently, I am using one route with a variable (which is the action, e.g update name, email, password etc.) to send the updated user data to the server.</p>
  
  <p>I am using a switch statement that looks at the action, and does the relevant update to the user data.</p>
  
  <p>I'd like one validation function that also has a switch statement, which will determine what it needs to validate.</p>
  
  <p>Currently I have this so far...</p>
  
  <p>this validation rules:</p>
  
  <pre><code>const validationRules = () =&gt; {
    console.log("validating...");
  
    return [
      // names must be 1 or more
      body("firstName").isLength({ min: 1 }),
      body("lastName").isLength({ min: 1 }),
    ];
  };
  
  </code></pre>
  
  <p>the post request:</p>
  
  <pre><code>app.post(
    "/api/user/update/:action",
    validationRules(),
    validate,
    (req, res) =&gt; {
      const { id } = req.body;
      const { action } = req.params;
  
      const updateDatabase = (id, updateObject) =&gt; {
        UserModel.findOneAndUpdate(
          { _id: id },
          { $set: updateObject },
          {
            useFindAndModify: false,
          }
        )
          .then((user) =&gt; {
            console.log(user);
            res.sendStatus(200);
          })
          .catch((err) =&gt; {
            console.log(err);
            res.status(403).send({ error: err });
          });
      };
  
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.array() });
      } else {
        let update = {};
  
        switch (action) {
          case "name":
            const { firstName, lastName } = req.body;
            update = {
              "userInfo.firstName": firstName,
              "userInfo.lastName": lastName,
            };
            break;
  
          case "email":
            const { email } = req.body;
            console.log(email);
            update = {
              "userInfo.email": email,
            };
            break;
  
          case "mobile":
            const { mobile } = req.body;
            update = {
              "userInfo.mobile": mobile,
            };
            break;
          default:
            console.log("nothing matched so nothing updated");
            break;
        }
        updateDatabase(id, update);
      }
    }
  );
  </code></pre>