Express-validator .getValidationResult()

2.3k views Asked by At

I'm working on a simple login for a web application, and can't seem handle .getValidationResult() correctly. I've spent quite a bit of time pouring over the npm documentation for express-validator, trying to find an answer in tutorials, and looking on sites like Stack Overflow without managing to find the answer to my question. Perhaps I just don't know the right question to ask.

I want to ensure that

  1. the user submitted something that has the form of an email address,
  2. that the password isn't empty. I then want to
  3. sanitize the email before interacting with the DB later on, then
  4. check to see if any of the first 3 procedures failed. If there were failures, return the user to the login page.

My question is what is the correct way to use express-validator's .getValidationResult()?

Here's the offending piece of code:

export let postLogin = (req: Request, res: Response, next: NextFunction) => {
  req.assert("email", "Email is not valid").isEmail();
  req.assert("password", "Password cannot be blank").notEmpty();
  req.sanitize("email").normalizeEmail({ gmail_remove_dots: false });

  req.getValidationResult().then(function(result){
      if (result != undefined) {
        console.log(result.array();
        return res.redirect("/login");
      }
    });

//do other login related stuff
}

I'm guessing that something simple is causing my error here, but I can't seem to find what it is.

1

There are 1 answers

0
C.Unbay On

It returns a promise for an object called Validation Object. This object contains information about the errors that your application has had.

The explanation.

Runs all validations and returns a validation result object for the errors gathered, for both sync and async validators.

All it does is returning errors if there is one. Here is some example code returned by that function.

//The error object

{
  "msg": "The error message",
  "param": "param.name.with.index[0]",
  "value": "param value",
  // Location of the param that generated this error.
  // It's either body, query, params, cookies or headers.
  "location": "body",

  // nestedErrors only exist when using the oneOf function
  "nestedErrors": [{ ... }]
}

The function returns isEmpty() when there is no errors to display.

The function returns .array([options]) if there are any errors. Errors are located in [options] array.

Check out this link for the example code of what it might return.

UPDATE

You can also just use it like this, which is easier.
Please note that this is new API as of v4.0.0 release of express-validator.

const { check, validationResult } = require('express-validator/check');
//go to a link    

app.get('/myURL', (req, res, next) => {
      // Get the validation result\
      const errors = validationResult(req).throw();
      if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors }); //err.mapped() 
 });