如何在React Hook Form中设置带有验证的自定义警告



如果验证失败,所以id不是githubid1githubid2,那么我将显示类似Please set an existing GihHub ID的自定义消息。可以设置它吗?

<FormControl fullWidth sx={{ mb: 6 }}>
<Controller
name="username"
control={control}
rules={{
validate: (v) => { // <-----------
return v == "githubid1" || v == "githubid2";
},
}}
render={({ field: { value, onChange } }) => (
<TextField
value={value}
label="Username"
onChange={onChange}
placeholder="johndoe"
error={Boolean(errors.username)}
/>
)}
/>
{errors.username && (
<FormHelperText sx={{ color: "error.main" }}>
{errors.username.message}
</FormHelperText>
)}
</FormControl>
const [customError, setCustomError] = useState('');
<FormControl fullWidth sx={{ mb: 6 }}>
<Controller
name="username"
control={control}
rules={{
validate: (v) => {
if (v !== "githubid1" || v !== "githubid2") {
setCustomError('Your custom text here');
}

return v == "githubid1" || v == "githubid2";
},
}}
render={({ field: { value, onChange } }) => (
<TextField
value={value}
label="Username"
onChange={onChange}
placeholder="johndoe"
error={Boolean(errors.username)}
/>
)}
/>
{errors.username || customError && (
<FormHelperText sx={{ color: "error.main" }}>
{errors.username.message || customError}
</FormHelperText>
)}
</FormControl>

最新更新