If validation fails, so id is not githubid1
, or githubid2
then I would show a custom message like Please set an existing GihHub ID
. Is it possible to set it?
<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>
CodePudding user response:
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>