Search code examples
javascriptnode.jsexpressvalidation

Is there a standard way to do backend validation?


I'm writing a simple CRUD application in express.js and node.js and while developing the backend APIs this is what I came up with

app.post("/signup", (req, res) => {
  const { name, email, password } = req.body;
  if (!name) {
    res.status(401).json("Please provide a name.");
  } else if (!email) {
    res.status(401).json("Please provide an email.");
  } else if (!password) {
    res.status(401).json("Please provide a password.");
  }
});

Is there a better way to do this? I want to make sure that even if the frontend required HTML input fields are bypassed, the data is still validated in the backend.


Solution

  • I'd recommend combining them into a single response. Otherwise the user may correct one error only to be presented with another, and wondering why both errors weren't shown in the first place.

    Maybe something like:

    app.post("/signup", (req, res) => {
      const { name, email, password } = req.body;
    
      const errs = [];
      if (!name) {
        errs.push("Please provide a name.");
      }
      if (!email) {
        errs.push("Please provide an email.");
      }
      if (!password) {
        errs.push("Please provide a password.");
      }
    
      if (errs.length > 0) {
        res.status(401).json(errs);
      } else {
        // handle success here
      }
    });