刚开始写了一个密码确认发现只能先输密码,后输入确认密码,否则提示语无法消失
<ProForm
form={form}
layout="horizontal"
key="form"
>
<ProFormText.Password
allowClear
label="密码"
placeholder="密码长度为6-18个字符"
rules={[
{
required: true,
message: '密码为必填项',
},
{
pattern: /^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]{6,18}$/,
message: '密码长度为6-18位,必须由字母、数字组成',
},
]}
width="md"
name="passWord"
/>
<ProFormText.Password
allowClear
label="确认密码"
placeholder="确认密码长度为6-18个字符"
rules={[
{
required: true,
message: '确认密码为必填项',
},
({ getFieldValue }) => ({
validator(_: any, value: any) {
if (!value || getFieldValue('passWord') === value) {
return Promise.resolve();
}
return Promise.reject(new Error('两次密码不一致'));
},
}),
]}
width="md"
name="confirmPassword"
/>
</ProForm>
后面发现f可以在输入密码时单独调用form中的校验方法来解决此问题
<ProForm
form={form}
layout="horizontal"
key="form"
>
<ProFormText.Password
allowClear
label="密码"
placeholder="密码长度为6-18个字符"
rules={[
{
required: true,
message: '密码为必填项',
},
{
pattern: /^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]{6,18}$/,
message: '密码长度为6-18位,必须由字母、数字组成',
},
]}
width="md"
onChange={passWordChange}
name="passWord"
/>
<ProFormText.Password
allowClear
label="确认密码"
placeholder="确认密码长度为6-18个字符"
rules={[
{
required: true,
message: '确认密码为必填项',
},
({ getFieldValue }) => ({
validator(_: any, value: any) {
if (!value || getFieldValue('passWord') === value) {
return Promise.resolve();
}
return Promise.reject(new Error('两次密码不一致'));
},
}),
]}
width="md"
name="confirmPassword"
/>
</ProForm>
//定义输入密码时的回调事件
const passWordChange: any = () => {
const confirmPasswordValue = form.getFieldValue('confirmPassword') //获取确认密码的值
if (confirmPasswordValue) {
form.validateFields(['confirmPassword']);//使用form.validateFields(),一个参数时校验某一项,若不传参则校验全部
}
}