Как получить определенные элементы из массива экспресс-проверки? - PullRequest
0 голосов
/ 08 июля 2019

Как я могу просто получить объект "msg" из errors.array()?

Вывод всего массива выглядит следующим образом: [{"value":"abc","msg":"Your email is not valid","param":"email","location":"body"}]

Я пытался указать "msg"объект с errors.array()[1], но он ничего не возвратил.

  router.post("/signup",
  [
    check('email', 'Your email is not valid').not().isEmpty().isEmail().normalizeEmail(),
    check('password', 'Your password must be at least 5 characters').not().isEmpty().isLength({min: 5})
  ],
  function (req, res, next) {
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
      res.render("user/signup", {
        hasErrors: JSON.stringify(errors.array()[1])
      });
    } else {
      //...
    }
  });

Ошибка вывода в моем статическом файле:

<h2 style="color: red;">{{hasErrors}}</h2>

1 Ответ

0 голосов
/ 08 июля 2019

Вы можете использовать .array() или .mapped(), если хотите получить доступ к ошибкам.В противном случае вы можете использовать .formatWith, как показано в doc:

app.post('/create-user', yourValidationChains, (req, res) => {
  // errors will be like [{ myLocation: 'body' }, { myLocation: 'query' }], etc
  const errors = myValidationResult(req).array();
});

или в формате :

app.post('/create-user', yourValidationChains, (req, res, next) => {
  const errorFormatter = ({ location, msg, param, value, nestedErrors }) => {
    // Build your resulting errors however you want! String, object, whatever - it works!
    return `${location}[${param}]: ${msg}`;
  };
  const result = validationResult(req).formatWith(errorFormatter);
  if (!result.isEmpty()) {
    // Response will contain something like
    // { errors: [ "body[password]: must be at least 10 chars long" ] }
    return res.json({ errors: result.array() });
  }

  // Handle your request as if no errors happened
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...