1.使用AntD form表单的rule校验
进入AntD官网的form表单模块 https://ant.design/components/form-cn
选择自己想要使用的表单样式,查看源码如何使用,将其运用到自己的项目中:
首先,不要忘记引入 import { Form } from "antd";(在此之前也要先安装AntD库才可以)
回到自己的项目中,我这里要做一个注册页的表单校验:
初步构建好大致表单,rules只设置了一个条规则:required必填,message是未填写时的红字提示信息
<Form labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} onFinish={onFinish}>
<Form.Item
label="用户名"
name="username"
rules={[
{ required: true, message: '请输入用户名' }
]}
>
<Input />
</Form.Item>
<Form.Item
label="密码"
name="password"
rules={[{ required: true, message: '请输入密码' }]}
>
{/* 密码加密形式 */}
<Input.Password />
</Form.Item>
<Form.Item
label="确认密码"
name="confirm"
rules={[{ required: true, message: '请再次输入密码' }]}
>
<Input.Password />
</Form.Item>
<Form.Item label="昵称" name="nickname">
<Input />
</Form.Item>
<Form.Item wrapperCol={{ span: 16, offset: 6 }}>
<Space>
<Button type="primary" htmlType="submit">
注册
</Button>
<Link to={LOGIN_PATHNAME}>已有账号?去登录</Link>
</Space>
</Form.Item>
</Form>
注意观察,rules是一个数组形式,里面可以设置多条,我们再来给用户名校验增加两条:
{ type: 'string', min: 5, max: 20, message: '字符长度在5-20之间' },这条规则的意思是:
-
类型必须是字符串(
type: 'string'
); -
长度限制在 5 到 20 个字符之间(
min: 5
,max: 20
); -
如果不满足这个条件,就提示信息:“字符长度在5-20之间”。
{ pattern: /^\w+$/, message: '只能输入字母数字下划线' },这条规则使用了一个正则表达式进行校验:
-
^\w+$
表示:字符串必须是由 字母、数字或下划线组成,并且 不能有其他字符;-
^
和$
表示开头和结尾,确保整条字符串都匹配; -
\w
是一个正则简写,表示 字母(a-zA-Z)+ 数字(0-9)+ 下划线(_); -
+
表示至少出现一次。
-
<Form.Item
label="用户名"
name="username"
rules={[
{ required: true, message: '请输入用户名' },
{ type: 'string', min: 5, max: 20, message: '字符长度在5-20之间' },
// 这是一个正则表达式
{ pattern: /^\w+$/, message: '只能输入字母数字下划线' },
]}
>
<Input />
</Form.Item>
最后,再讲一下确认密码的验证逻辑:
我们自定义了一个校验函数validator
-
getFieldValue('password')
:获取用户输入的原始密码(上面那个输入框中的密码)。 -
value
:当前确认密码输入框的值。
验证逻辑是:
-
如果
value
为空 或者value === password
,说明验证通过; -
否则,抛出一个错误提示:“两次密码不一致”。
dependencies: ['password']
-
表示这个字段依赖于
password
字段; -
如果用户修改了密码,确认密码的验证也会自动重新触发(保持同步)。
<Form.Item
label="确认密码"
name="confirm"
dependencies={['password']} //依赖于password,变化会重新触发验证
rules={[
{ required: true, message: '请输入密码' },
({ getFieldValue }) => ({
validator(_, value) {
if (!value || getFieldValue('password') === value) {
return Promise.resolve()
} else {
return Promise.reject(new Error('两次密码不一致'))
}
},
}),
]}
>
<Input.Password />
</Form.Item>
当不一致的时候,触发校验错误:
2.第三方校验工具React-Hook-Form
网址https://react-hook-form.com/
由于我也没有在项目中使用过这个,下面是向ai请教的简单上手步骤,参考一下:
🚀 一、React Hook Form 是什么?
React Hook Form 是基于 React 的 Hooks API(如 useForm
) 构建的表单处理库,特点是:
✅ 性能高 —— 避免多余渲染
✅ 简洁易用 —— API 简洁
✅ 易于集成 —— 能方便与 UI 库(如 Ant Design、Material UI)结合使用
🛠️ 二、安装方式
npm install react-hook-form
或者:
yarn add react-hook-form
🧪 三、最基础的使用示例
import React from 'react'
import { useForm } from 'react-hook-form'
function MyForm() {
//解构出需要的字段
const {
register, // 注册表单字段
handleSubmit, // 提交处理函数
formState: { errors }, // 表单校验错误
} = useForm()
const onSubmit = data => {
console.log('表单提交数据:', data)
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label>用户名:</label>
<input {...register('username', { required: '用户名不能为空' })} />
{errors.username && <p>{errors.username.message}</p>}
</div>
<div>
<label>密码:</label>
<input
type="password"
{...register('password', {
required: '密码不能为空',
minLength: { value: 6, message: '密码最少6位' }
})}
/>
{errors.password && <p>{errors.password.message}</p>}
</div>
<button type="submit">提交</button>
</form>
)
}
export default MyForm
💡 四、重要 API 解释
API | 作用 |
---|---|
useForm() | 初始化表单状态与方法 |
register(name, options) | 注册表单字段与校验规则 |
handleSubmit(onValid) | 封装提交行为,验证成功后执行回调 |
formState.errors | 存储所有校验错误 |
reset() | 重置表单字段 |
watch() | 实时监听表单字段值变化 |
🧩 五、常见校验规则
register('email', {
required: '邮箱不能为空',
pattern: {
value: /^\S+@\S+$/i,
message: '邮箱格式错误'
}
})