Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
  }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading