You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将express-validator的req.validationErrors()返回至前端?

解决express-validator验证错误信息返回前端并展示的问题

我来帮你搞定这个问题,分后端和前端两部分调整就能实现需求:


第一步:后端返回错误信息

你已经通过req.validationErrors()拿到了验证错误数组,现在只需要把它以JSON格式返回给前端,同时返回422状态码(这是HTTP标准中专门表示「无法处理的实体」的状态码,非常适合验证失败的场景)。修改你的后端代码:

app.post('/sign-in', (req, res, next) => {
  // 你的验证规则(这里补充了邮箱和密码确认的示例,根据你的实际需求调整)
  req.checkBody('name', 'Please write your name').notEmpty();
  req.checkBody('username', 'Please write your username').notEmpty();
  req.checkBody('email', 'Please enter a valid email').isEmail();
  req.checkBody('password', 'Password is required').notEmpty();
  req.checkBody('confirm-password', 'Passwords do not match').equals(req.body.password);

  const errors = req.validationErrors();
  if (errors) {
    // 返回422状态码+错误数组
    return res.status(422).json({ errors: errors });
  } else {
    // 你的正常业务逻辑(比如创建用户)
    res.status(200).send('Sign-in successful');
  }
});

第二步:前端接收并展示错误信息

前端需要先解析422响应的JSON数据,再把错误信息对应到每个表单字段下方。先修改fetch请求代码,再添加一个错误展示函数:

修改fetch请求代码

注意要添加Content-Type请求头,确保后端能正确解析JSON格式的请求体:

document.getElementById('sign-in').addEventListener('submit', event => {
  event.preventDefault();
  const name = document.getElementById('name').value;
  const username = document.getElementById('username').value;
  const email = document.getElementById('email').value;
  const password = document.getElementById('password').value;
  const confirmPassword = document.getElementById('confirm-password').value;

  window.fetch(`${config.serverHost}/sign-in`, {
    method: 'post',
    headers: {
      'Content-Type': 'application/json', // 必须添加这个头
    },
    body: JSON.stringify({ 
      name, 
      username, 
      email, 
      password, 
      'confirm-password': confirmPassword 
    })
  }).then(res => {
    if (res.status === 200) {
      window.parent.location.reload();
    } else if (res.status === 422) {
      // 解析响应体中的错误数据
      return res.json();
    }
    // 处理其他异常状态
    throw new Error('Request failed unexpectedly');
  }).then(data => {
    if (data && data.errors) {
      // 调用函数展示错误
      displayErrors(data.errors);
    }
  }).catch(err => {
    console.error('请求出错:', err);
  });
});

添加错误展示函数

这个函数会把错误提示放到对应输入框的下方,同时先清除之前的错误提示,避免重复显示:

function displayErrors(errors) {
  // 清除所有已存在的错误提示
  document.querySelectorAll('.error-message').forEach(el => el.remove());

  errors.forEach(error => {
    // 根据错误的param字段找到对应的输入框(需要给input加name属性)
    const input = document.querySelector(`input[name="${error.param}"]`);
    if (input) {
      // 创建错误提示元素
      const errorDiv = document.createElement('div');
      errorDiv.className = 'error-message text-danger'; // 用Bootstrap的text-danger类显示红色提示
      errorDiv.textContent = error.msg;
      // 把错误提示插入到输入框的父元素中
      input.parentElement.appendChild(errorDiv);
    }
  });
}

关键注意事项

你当前的前端表单input缺少name属性,这是必须补充的!因为express-validator的req.checkBody('name')是根据请求体里的键匹配的,而你的fetch请求里传的是name、username等字段,所以要给每个input加上对应的name属性,比如:

<input id="name" name="name" type="text" class="form-control" placeholder="name" autocomplete="family-name">
<input id="username" name="username" type="text" class="form-control" placeholder="username" autocomplete="given-name">
<input id="email" name="email" class="form-control" type="email" placeholder="monemail@gmail.com" autocomplete="email">
<input id="password" name="password" class="form-control" type="password" autocomplete="current-password">
<input id="confirm-password" name="confirm-password" class="form-control" type="password" autocomplete="current-password">

这样displayErrors函数才能通过name属性找到对应的输入框,错误提示才能精准显示在对应位置。

内容的提问来源于stack exchange,提问作者C0G1T0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:05:39