Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set custom warning with validation in React Hook Form?

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading