2

Expected behaviour: When the form submit button is hit before anything is in the text input, the error message is displayed.

Current behaviour: The error message is only displayed once in input has a value, even after hitting submit. Meaning the user has to click on and type in the textfield before the error message will appear.

Minimal codesandbox demo

I know it was possible to do this in earlier versions of react-hook-form, I think it was the default behaviour actually, surely theres still a way? It seems so simple.

<form className="App" onSubmit={handleSubmit(submitForm)}>
      <TextField
        label="Attribution"
        variant="outlined"
        helperText={
          Boolean(errors.attribution)
            ? errors.attribution.message
            : "Who is being quoted?"
        }
        {...register("attribution", {
          required: true,
          minLength: { value: 3, message: "Please enter a longer name" },
          maxLength: { value: 50, message: "Please enter a shorter name" }
        })}
        error={Boolean(errors.attribution)}
      />
      <Button type="submit">Submit</Button>
    </form>

2 Answers 2

4

Okay I realised it can be fixed easily by changing

{...register("attribution", {
          required: true,
          minLength: { value: 3, message: "Please enter a longer name" },
          maxLength: { value: 50, message: "Please enter a shorter name" }
        })}

to

{...register("attribution", {
          required: 'Your name is required', // <- right here
          minLength: { value: 3, message: "Please enter a longer name" },
          maxLength: { value: 50, message: "Please enter a shorter name" }
        })}

Very cool.

Relevant react-hook-form docs.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to provide a message, otherwise the field will just turn red

{...register("attribution", {
   required: { value: true, message: "Field is required" },
   minLength: { value: 3, message: "Please enter a longer name" },
   maxLength: { value: 50, message: "Please enter a shorter name" }
})}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.