在输入确认密码的时候,输入框下会同步弹出提示,降低用户体验,这里需要用到两个属性:
validateTrigger 和 dependencies
设置validateTrigger={['onBlur']}, 这样就会在失去焦点的时候才触发验证
代码如下:
import React from "react";
import "./App.css";
import { Form, Button, Input } from "antd";
function App() {
const [form] = Form.useForm();
const ruleRequire = { required: true, message: "此项不能为空" };
const validatePsw = ({ getFieldValue }) => {
return {
validator: (_, value) => {
if (!value || getFieldValue("password") === value) {
return Promise.resolve();
}
return Promise.reject(new Error("两次输入密码不一致,请重新输入!"));
},
};
};
return (
<div
className="App"
style={{
height: "100vh",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<div className="FormBox">
<Form
style={{ width: "600px" }}
form={form}
name="testForm"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
>
<Form.Item name="account" label="账号" rules={[ruleRequire]}>
<Input placeholder="请输入"></Input>
</Form.Item>
<Form.Item name="password" label="密码" rules={[ruleRequire]}>
<Input.Password placeholder="请输入"></Input.Password>
</Form.Item>
<Form.Item
name="confirmPsw"
label="确认密码"
dependencies={["password"]}
validateTrigger="onBlur"
rules={[validatePsw]}
>
<Input.Password placeholder="请输入"></Input.Password>
</Form.Item>
<Form.Item wrapperCol={{ offset: 8, span: 16 }}>
<Button type="primary">提交</Button>
</Form.Item>
</Form>
</div>
</div>
);
}
export default App;