1

I'm trying to create form with React Hook Form with Material UI TextField. It seems I configured it properly but the error message doesn't appear and I don't know why. I put just the main parts of the code.

import { TextField } from "@material-ui/core";
import { Controller, useForm } from "react-hook-form";

type NovoSinistroForm = {
    codigoCobertura: number;
    telefoneResponsavel: string;
    evento: number;
    dataEvento: Date;
    dataEstimadaColheita: Date;
    areaAtingida: number;
    nomeComunicante: string;
    nomeResponsavelVistoria: string;
    relacaoComunicanteResponsavel: string;
    emailComunicante: string;
    telefone1Comunicante: string;
    telefone2Comucante: string;
}

const {
        control,
        formState,
        handleSubmit,
        watch,
} = useForm<NovoSinistroForm>();

<form onSubmit={onSubmit}>
   <Controller
    name="nomeResponsavelVistoria"
    control={control}
    rules={{
        required:{
            value: true,
            message: "Campo obrigatório."
        }
    }}
    render={({
        field,
        fieldState: { invalid, isTouched, isDirty, error },
    }) => (
        <TextField
            {...field}
            innerRef={field.ref}
            label="Responsável por vistoria"
            type="text"
            InputLabelProps={{
                shrink: true,
            }}
            error={invalid && isTouched}
            helperText={error?.message}
        />
    )}
/>
</form>

OnBlur doesn't seem to be firing enter image description here

1 Answer 1

3

I finnaly figured it out what the problem was. I had to pass an objet into useForm to configure the validation strategy before user submit the form.

const {
        control,
        formState,
        handleSubmit,
        watch,
    } = useForm<NovoSinistroForm>({
        mode: 'onTouched'
    });

I hope it can help someone else in future.

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

1 Comment

I was facing the same problem, but was able to generate the helper text without doing what you did. But the helper text is not changing for the masked field. Can you take a look since you already solved this problem once?

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.