0

此代码工作正常。它抛出错误并显示在网页上。但现在我想挑选个别错误并显示到网页上。

    // request.body validation
  req.checkBody('email', 'Email is required.').notEmpty();
  req.checkBody('name', 'Name is required.').notEmpty();
  req.checkBody('phone', 'Phone is required.').isMobilePhone('en-IN');
  req.checkBody('password1', 'Password is required.').isLength({min:6});
  req.checkBody('password2', 'Password not same, try again!!').equals(password1);

  var errors = req.validationErrors();

  if (errors) {
    console.log(req.body.params.errors);
    res.render('form', {
      errors: errors,
      isForm: true,
      register: true
    });
  } else {
    console.log('PASSED');
  }

console.log 错误的各个参数的代码是什么?

4

2 回答 2

1

最简单的方法是打开mapped. 这使errors数组成为普通对象,因此您可以使用点语法访问特定错误:

  var errors = req.validationErrors(true);  // note the true argument

  if (errors) {
    console.log(errors);

    res.render('form', {
      errors: errors.phone,  // ordinary object access syntax
      isForm: true,
      register: true
    });
  } else {
    console.log('PASSED');
  }

您也可以将映射设置为 false。这是默认方式。

然后该errors变量是一个数组,因此您可以像在任何其他数组中一样访问它的元素:

  if (errors) {
    res.render('form', {
      errors: errors[0], // only the first error
      isForm: true,
      register: true
    });
  } else {
    console.log('PASSED');
  }

如果要发送属于特定字段的元素,可以使用 for 循环在以下位置查找其位置errors

  // request.body validation
  req.checkBody('email', 'Email is required.').notEmpty();
  req.checkBody('name', 'Name is required.').notEmpty();
  req.checkBody('phone', 'Phone is required.').isMobilePhone('en-IN');
  req.checkBody('password1', 'Password is required.').isLength({ min: 6 });
  req.checkBody('password2', 'Password not same, try again!!').equals('password1');

  var errors = req.validationErrors();

  if (errors) {
    // look for phone
    let indexOfPhone = -1;
    for (let i = 0; i < errors.length; i += 1) {
      if (errors[i].param === 'phone') indexOfPhone = i;
    }

    res.render('form', {
      errors: errors[indexOfPhone],
      isForm: true,
      register: true
    });
  } else {
    console.log('PASSED');
  }
于 2018-03-15T21:56:18.733 回答
1

当错误变量有一个或多个值转储在其中时,使用简单的 for 循环打印参数req.validationErrors()

req.checkBody('email', 'Email is required.').notEmpty();
req.checkBody('name', 'Name is required.').notEmpty();
req.checkBody('phone', 'Phone is required.').isMobilePhone('enIN');
req.checkBody('password1', 'Password is required.').isLength({min:6});
req.checkBody('password2', 'Password not same, try again!!').equals(password1);

var errors = req.validationErrors();

if (errors) {
  // true condition : errors has values stored in it
  // printing out the params of each error using a for loop
  var i;
  for (i = 0; i < errors.length;i++) 
  { 
    console.log(i," : ",errors[i]['param']); // printing out the params
  }
  res.render('form', {
  errors: errors,
  isForm: true,
  register: true
  });
} else {
  // false condition : errors is empty
  console.log('PASSED');
}
于 2018-08-31T05:44:52.780 回答