【发布时间】:2020-07-07 11:01:31
【问题描述】:
在处理 React-hook-form 时进行输入字段匹配验证的最佳做法是什么?比如匹配email输入等时
在使用 React-hook-form 研究电子邮件匹配验证时,在尝试通过其验证方法将错误消息与“耦合元素”分开时发现了一个问题。 ref 只接受一个参数,用于 React-hook-form register,而需要使用useRef 访问current.value 进行值匹配,如下:
import React, { useRef } from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";
function App() {
const { register, handleSubmit, errors } = useForm();
const inputEmail = useRef(null)
const onSubmit = data => {
console.log('onSubmit: ', JSON.stringify(data))
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label htmlFor="email">Email</label>
<input
name="email"
type="email"
ref={inputEmail}
/>
{/* desired: show `email` error message */}
<label htmlFor="email">Email confirmation</label>
<input
name="emailConfirmation"
type="email"
ref={register({
validate: {
emailEqual: value => (value === inputEmail.current.value) || 'Email confirmation error!',
}
})}
/>
{errors.emailConfirmation && <p>{errors.emailConfirmation.message}</p>}
<input type="submit" />
</form>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
虽然在进行输入字段匹配时,这种模式似乎是一种选择,但它与 React-hook-form 的配合并不好!
例如,错误消息仅与一个输入案例耦合,并且每个独立字段没有单独的消息,或者输入字段之一没有分配给它的寄存器,这意味着属性required是未设置等
所以,我正在寻找一个好的做法或模式来解决:
- 通过输入字段分隔错误消息
- 验证方法,在测试匹配时应该能够以符合 React 的方式引用双字段值,而不是 通过 DOM(document.querySelector 等)
【问题讨论】: