1 回答
TA贡献1865条经验 获得超7个赞
您需要message在required字段中添加,或者只是查询是否有错误:
<>
<input
name="firstName"
placeholder="First name"
ref={register({
required: 'invalid first name'
})}
/>
<span> {errors.firstName && errors.firstName.message}</span>
</>
// Or
<>
<input
placeholder="Last name"
className="mkn-input"
name="lastName"
ref={register({
required: true,
pattern: /^[A-Za-z]+$/i
})}
/>
{errors.lastName && <span>Invalid last name</span>}
</>
// Or https://react-hook-form.com/advanced-usage#ErrorMessage
function App() {
const { register, handleSubmit, errors } = useForm();
const onSubmit = data => {
console.log(data);
};
return (
<div className="App">
<header className="App-header">
<form onSubmit={handleSubmit(onSubmit)}>
<input
className="mkn-input"
name="firstName"
placeholder="First name"
ref={register({
required: 'invalid first name'
})}
/>
<span> {errors.firstName && errors.firstName.message}</span>
<input
placeholder="Last name"
className="mkn-input"
name="lastName"
ref={register({
required: true,
pattern: /^[A-Za-z]+$/i
})}
/>
{errors.lastName && <span>Invalid last name</span>}
<input
name="age"
type="number"
placeholder="Age"
className="mkn-input"
ref={register({ min: 18, max: 99 })}
/>
<input type="submit" className="mkn-btn" />
</form>
</header>
</div>
);
}
添加回答
举报