React / 系统课时

表单校验与错误提示

表单校验与错误提示

本课将在受控表单基础上实现必填、格式和长度校验,并区分字段级错误与提交级错误。完成后,用户能在合适的时机看到明确提示,表单也只会在数据合法时提交。

学习目标

  • 能为字段编写可复用的同步校验规则
  • 掌握失焦校验与提交校验的配合方式
  • 能设计字段级错误和提交级错误提示

先设计校验时机

表单校验不仅要判断“是否正确”,还要决定“何时提示”。用户尚未操作字段时立即显示错误,容易造成干扰;只在提交时统一提示,又会让用户难以定位问题。

常见策略是:字段失焦后显示该字段错误,提交时校验全部字段。这样既能及时反馈,也能保证提交前不会漏检。

表单校验与错误提示流程

校验结果应存成以字段名为键的对象,例如 { email: '邮箱格式不正确' }。字段没有错误时不要写空提示,而是删除该键或返回空字符串后统一过滤。

完整校验示例

下面的代码可以直接替换 Vite 项目的 src/main.jsx。它包含必填、邮箱格式和密码长度校验,并在失焦与提交时复用同一套规则。

jsx
import React, { useState } from 'react';
import { createRoot } from 'react-dom/client';

function validate(values) {
  const errors = {};

  if (!values.email.trim()) {
    errors.email = '请输入邮箱';
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) {
    errors.email = '邮箱格式不正确';
  }

  if (!values.password) {
    errors.password = '请输入密码';
  } else if (values.password.length < 8) {
    errors.password = '密码至少需要 8 个字符';
  } else if (values.password.length > 20) {
    errors.password = '密码不能超过 20 个字符';
  }

  return errors;
}

function App() {
  const [values, setValues] = useState({ email: '', password: '' });
  const [errors, setErrors] = useState({});
  const [touched, setTouched] = useState({});
  const [submitMessage, setSubmitMessage] = useState('');

  function handleChange(event) {
    const { name, value } = event.target;
    const nextValues = { ...values, [name]: value };
    setValues(nextValues);

    if (touched[name]) {
      setErrors(validate(nextValues));
    }
  }

  function handleBlur(event) {
    const { name } = event.target;
    setTouched((current) => ({ ...current, [name]: true }));
    setErrors(validate(values));
  }

  function handleSubmit(event) {
    event.preventDefault();
    const nextErrors = validate(values);
    setErrors(nextErrors);
    setTouched({ email: true, password: true });

    if (Object.keys(nextErrors).length > 0) {
      setSubmitMessage('提交失败,请修正表单中的错误');
      return;
    }

    setSubmitMessage('校验通过,表单可以提交');
    console.log(values);
  }

  return (
    <form onSubmit={handleSubmit} noValidate>
      {submitMessage && <p role="status">{submitMessage}</p>}

      <label htmlFor="email">邮箱</label>
      <input
        id="email"
        name="email"
        type="email"
        value={values.email}
        onChange={handleChange}
        onBlur={handleBlur}
        aria-invalid={Boolean(touched.email && errors.email)}
        aria-describedby={errors.email ? 'email-error' : undefined}
      />
      {touched.email && errors.email && (
        <p id="email-error" role="alert">{errors.email}</p>
      )}

      <label htmlFor="password">密码</label>
      <input
        id="password"
        name="password"
        type="password"
        value={values.password}
        onChange={handleChange}
        onBlur={handleBlur}
        aria-invalid={Boolean(touched.password && errors.password)}
        aria-describedby={errors.password ? 'password-error' : undefined}
      />
      {touched.password && errors.password && (
        <p id="password-error" role="alert">{errors.password}</p>
      )}

      <button type="submit">注册</button>
    </form>
  );
}

createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

预期结果

text
1. 邮箱为空并失焦时,字段下方显示“请输入邮箱”。
2. 输入非法邮箱时,显示“邮箱格式不正确”。
3. 密码少于 8 个字符时,显示“密码至少需要 8 个字符”。
4. 点击提交且存在错误时,顶部显示“提交失败,请修正表单中的错误”。
5. 两个字段都合法时,顶部显示“校验通过,表单可以提交”,控制台输出表单数据。

示例中的邮箱正则用于常见格式检查,不等价于完整的邮件地址标准。真实系统仍需由服务端确认邮箱是否存在、是否重复以及数据是否符合业务规则。

字段级错误与提交级错误

字段级错误应紧邻对应控件,内容要说明具体问题,例如“密码至少需要 8 个字符”,不要只写“输入有误”。提交级错误用于概括整体状态,例如“请修正表单中的错误”,不应替代字段旁的具体说明。

aria-invalid 告诉辅助技术当前字段是否无效,aria-describedby 将控件与错误文本关联。错误文本使用 role="alert",可以让屏幕阅读器更及时地感知变化。

提交成功提示与错误提示可以共用一个状态,但真实项目往往会拆分为 idle、submitting、success 和 error,以便处理接口请求、重复提交和网络失败。

校验规则的职责边界

前端校验用于快速反馈和减少无效请求,但不能替代服务端校验。浏览器中的代码可以被绕过,因此必填、长度、权限、唯一性和业务约束都应在服务端再次验证。

同步规则适合必填、格式和长度。用户名是否重复、优惠码是否有效等需要查询服务端的规则,应设计为异步校验,并处理加载状态、请求竞态与超时。

为了避免规则分散,建议让 validate 只接收表单值并返回错误对象。组件负责决定何时调用、何时展示,提交函数负责根据错误数量决定是否继续。

常见错误与改进

不要在每次渲染时无条件调用 setErrors,否则会触发重复渲染。校验应发生在事件处理函数、提交函数或经过控制的副作用中。

用户修改字段后,旧错误可能已经失效。示例在字段被触碰后重新校验整个表单,字段较多时可以只校验当前字段,以减少无关提示变化。

服务端返回提交失败时,不要把所有错误都塞进字段对象。能对应具体字段的错误写入字段级提示,网络异常或系统错误放在提交级区域,并保留用户已经输入的内容。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

表单校验与错误提示

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通