我有一个表格(很长很抱歉),对于用户来说,输入姓名,电子邮件,电话,评论非常简单:
<form
className={classes.root}
data-testid="getting-started-form"
onSubmit={handleSubmit(onSubmit)}
>
<div style={{ width: '400px' }}>
<div style={{ width: '100%'}}>
<Controller as={<TextField
label="Name"
id="name"
name="name"
type="text"
value={name}
placeholder="Name"
onChange={(e: React.FormEvent<EventTarget>) => {
let target = e.target as HTMLInputElement;
setName(target.value);
}}
inputProps={{
'data-testid': 'name'
}}
/>} name="name" rules={{ required: true }} control={control}
/>
{errors.name && <span>Name is required</span>}
</div>
<div style={{ width: '100%' }}>
<Controller as={<TextField
label="Email"
id="email"
name="email"
type="text"
value={email}
placeholder="Email"
style={{ width: '100%' }}
onChange={(e: React.FormEvent<EventTarget>) => {
let target = e.target as HTMLInputElement;
setEmail(target.value);
}}
inputProps={{
'data-testid': 'email'
}}
/>} name="email" rules={{ required: true, pattern: /^\w+[\w-\.]*\@\w+((-\w+)|(\w*))\.[a-z]{2,3}$/i }} control={control}
/>
{errors.email && <span>Email is required</span>}
</div>
<div style={{ width: '30%' }}>
<Controller as={<TextField
label="Phone"
id="phone"
name="phone"
type="text"
value={phone}
placeholder="eg.15556667890"
onChange={(e: React.FormEvent<EventTarget>) => {
let target = e.target as HTMLInputElement;
setPhone(target.value);
}}
inputProps={{
'data-testid': 'phone'
}}
/>} name="phone" rules={{ pattern: /\d{11}/ }} control={control}
/>
</div>
<div style={{ width: '30%' }}>
<Controller as={<TextField
label="Comments"
id="comments"
name="comments"
type="text"
value={comments}
placeholder="Comments"
rows={6}
multiline
onChange={(e: React.FormEvent<EventTarget>) => {
let target = e.target as HTMLInputElement;
setComments(target.value);
}}
inputProps={{
'data-testid': 'comments'
}}
/>} name="comments" control={control}
/>
</div>
</div>
<Button
type="submit"
aria-label="submit getting-started-form"
variant="contained"
color="primary"
data-testid="getting-started-form-submit-button"
>
Submit
</Button>
</form>
所有字段在提交时均经过验证。无论如何,在提交表单之前是否需要获取react-hook-forms进行某种验证?我想要像Angular这样的标志用于脏污,原始等。
答案 0 :(得分:1)
已更新! 验证程序API:https://react-hook-form.com/api/。
您可以选择值onBlur
而不是默认的onSubmit
模式。
您可以在此处关注官方文档:https://react-hook-form.com/get-started#Registerfields。
基本上,您需要register
个字段进行验证。然后react-hook-form
会在提交时自动为您验证。
答案 1 :(得分:-1)
我没有使用react-hook-forms,但是我已经使用onblur事件处理程序在提交之前验证各个字段。