react-hook-form 使用 useController 时设置自定义验证的错误消息

Chr*_*ris 9 reactjs react-hook-form

我使用 useController 进行文本输入,但无法为自定义验证设置错误消息。我假设我能够使用具有与内置验证类似的值/消息的对象,但TypeError: validateFunction is not a function如果我尝试这样做,则会收到错误。

这工作正常:

<TextInput
                control={control}
                name={`email`}
                label={`Email *`}
                rules={{
                    required:true,
                    validate: {
                        checkEmail: v => validateEmail(v)
                    }
                }}
            />
Run Code Online (Sandbox Code Playgroud)

我想做的事:

<TextInput
                control={control}
                name={`email`}
                label={`Email *`}
                rules={{
                    required:true,
                    validate: {
                        checkEmail: {
                            value: v => validateEmail(v),
                            message: 'Invalid email'
                        }
                    }
                }}
            />
Run Code Online (Sandbox Code Playgroud)

我的 TextInput 组件当前如下所示:

import style from "./form.module.scss"
import classnames from "classnames";
import { useController, useForm } from "react-hook-form";

export default function TextInput(props){

    const {
        field: { ref, ...inputProps },
        fieldState: { invalid, isTouched, isDirty },
        formState: { touchedFields, dirtyFields, errors }
    } = useController({
        name: props.name,
        control: props.control,
        rules: props.rules,
        defaultValue: props.defaultValue ? props.defaultValue : '',
    });


    return(
        <div className={classnames(style.fieldItem, {[style.error]: invalid})}>
            <label className={style.label}>{props.label}</label>
            <input
                className={style.textInput}
                inputRef={ref}
                type={`text`}
                placeholder={props.placeholder}
                {...inputProps}
            />
            {invalid &&
                <div className={style.message}>{`Invalid input`}</div>
            }
        </div>
    );

}
Run Code Online (Sandbox Code Playgroud)

使用此方法时如何设置自定义验证的错误消息?

kno*_*fel 20

对于使用自定义验证,validate您必须直接传递错误消息:

<TextInput
  control={control}
  name={`email`}
  label={`Email *`}
  rules={{
    required:true,
    validate: {
      checkEmail: v => validateEmail(v) || "ERROR MESSAGE"
    }
  }}
/>
Run Code Online (Sandbox Code Playgroud)

您可以在本节中阅读有关asregisterregisteror <Controller />areuseController使用相同rules接口的内容。