React Hook Form的required属性在TextField中不生效,无提示文本
React Hook Form 验证提示不显示的解决办法
问题根源
- 开启了
shouldUseNativeValidation: true,原生表单验证和MUI TextField的错误提示体系不兼容,React Hook Form的错误信息无法传递到组件上 - 未给TextField绑定
error和helperText属性,就算验证失败,组件也不知道要显示错误提示 - DesktopDatePicker直接用
register不匹配,它的value类型是Dayjs,需要专门做适配 - 提交按钮同时绑定了编辑切换和提交事件,导致验证逻辑被干扰
具体修复步骤
1. 关闭原生验证
修改useForm初始化配置,移除shouldUseNativeValidation: true,让React Hook Form接管验证逻辑:
const { register, handleSubmit, formState: { errors }, control } = useForm<Inputs>({ defaultValues: { firstName: patient.name?.firstName ?? '', lastName: patient.name?.lastName ?? '', birthdate: patient.birthDate ?? '', country: '', gender: patient.gender, email: patient.email ?? '', leveloftrust: patient.status?.levelOfTrust, lastsignedin: patient.status?.lastSignInAt, postalcode: patient.addresses[0]?.postalCode ?? '', city: patient.addresses[0]?.city ?? '', street: patient.addresses[0]?.lines[0] ?? '', }, // 移除shouldUseNativeValidation,默认关闭原生验证 });
2. 给TextField绑定错误状态
以firstName为例,修改TextField组件,添加错误状态和提示文本:
<TextField {...register('firstName', { required: 'Field needs to be filled out' })} label="Name" name="firstName" id="component-outlined" disabled={disabled} error={!!errors.firstName} helperText={errors.firstName?.message} />
lastName字段同理,照此修改即可。
3. 用Controller适配DatePicker
DesktopDatePicker不能直接用register,换成Controller组件来管理值和验证:
<LocalizationProvider dateAdapter={AdapterDayjs}> <Controller name="birthdate" control={control} rules={{ required: 'Field needs to be filled out' }} render={({ field, fieldState: { error } }) => ( <DesktopDatePicker label="Birthdate" inputFormat="MM/DD/YYYY" value={value} onChange={(newValue) => { setValue(newValue); field.onChange(newValue?.format('YYYY-MM-DD')); // 转换为字符串匹配表单类型 }} renderInput={(params) => ( <TextField {...params} error={!!error} helperText={error?.message} disabled={disabled} /> )} disabled={disabled} /> )} /> </LocalizationProvider>
4. 修复提交按钮逻辑
移除提交按钮上的onClick={handleEditClick},只保留type="submit",然后在onSubmit回调里切换禁用状态:
<Button size="large" type="submit" variant="contained"> {!disabled ? t('patient.setToComplete', 'Set to complete') : t('patient.edit', 'Edit')} </Button>
修改onSubmit函数:
const onSubmit = (data: Inputs) => { console.log(data); setDisabled(true); // 提交成功后切换回禁用状态 };
额外提示
如果其他字段(如gender、street)需要添加必填验证,同样要给对应的TextField绑定error和helperText属性,确保错误提示正常显示。
内容的提问来源于stack exchange,提问作者menab
相关产品推荐
相关产品推荐

