簡體   English   中英

使用 Material UI TextField 的 React Hook Form 驗證不起作用

[英]React Hook Form validation with Material UI TextField is not working

我正在嘗試使用帶有 Material UI TextField 的 React Hook Form 創建表單。 看來我配置正確,但沒有出現錯誤消息,我不知道為什么。 我只放了代碼的主要部分。

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 似乎沒有開火在此處輸入圖像描述

我終於弄清楚了問題所在。 在用戶提交表單之前,我必須將一個對象傳遞給 useForm 來配置驗證策略。

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

我希望它可以在未來幫助別人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM