如何从反应钩子表单创建自定义验证?

gec*_*cko 9 javascript reactjs react-hook-form

我想从下面的验证开始创建自定义验证。但到目前为止我还没有成功。我访问了这个网站并遵循了他的“自定义验证规则”中的代码,但我无法复制它。

isBefore方法工作正常,但验证却不行。我们如何通过自定义验证添加自定义消息?

const isBefore = (date1, date2) => moment(date1).isBefore(moment(date2));

const rules = {
    publishedDate: {
        required: 'The published date is required.',
        before: isBefore(scheduledDate, expiredDate)
    },
}

<Controller
    control={control}
    name="publishedDate"
    rules={rules.publishedDate}
    render={({ onChange }) => (
        <DatePicker
            className="mb-px-8"
            onChange={(value) => {
                setPublishedDate(value);
                onChange(value);
            }}
            minDate={new Date()}
            value={publishedDate}
        />
    )}
/>
Run Code Online (Sandbox Code Playgroud)

bow*_*ice 7

这是我的尝试:

您需要使用钩子 useEffect 和控制器。在页面顶部,您需要这两个导入:

import React, { useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
Run Code Online (Sandbox Code Playgroud)

那么您需要位于组件外部的验证函数。

const isBefore = (date) => {
  if (!date) {
    return false;
  }
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return date > today;
};
Run Code Online (Sandbox Code Playgroud)

上面的函数检查您选择的日期是将来的日期而不是过去的日期。

在您的组件下,您将所有内容设置为 useForm

const {
    register,
    handleSubmit,
    control,
    setValue,
    watch,
    errors,
    setError,
    clearError
  } = useForm();
Run Code Online (Sandbox Code Playgroud)

然后,您可以设置变量来监视日期选择器的更新,并设置 useEffect 来监视更改:

  const startDate = watch("startDate");
  useEffect(() => {
    register({ name: "startDate", type: "custom" }, { validate: { isBefore } });
  });


Run Code Online (Sandbox Code Playgroud)

然后,您在组件内部定义一个处理程序,用于处理数据更改和验证。

  const handleDateChange = (dateType) => (date) => {
    if (!isBefore(date)) {
      setError(dateType, "isBefore");
    } else {
      setError(dateType, "isBefore");
    }
    setValue(dateType, date);
    alert(date);
  };

Run Code Online (Sandbox Code Playgroud)

自定义错误消息可以存在于表单中的任何位置,并且您不需要将引用绑定到它。useForm() 和 watch('startDate') 为您控制数据。

这是可以存在于表单组件内任何位置的自定义错误消息。

请参阅更新的代码和框,其中我在提交按钮附近显示了自定义错误消息

              {errors.startDate && (
                <div variant="danger">
                  {errors.startDate.type === "isBefore" && (
                  <p>Please choose present or future date!</p>
                  )}
                </div>

Run Code Online (Sandbox Code Playgroud)

这是一个工作代码沙箱,我从昨天清理了一些,并添加了一些评论。 https://codesandbox.io/s/play-momentjs-forked-1hu4s?file=/src/index.js:1494-1802

如果您单击输入,然后选择过去的日期,然后单击提交,则会显示自定义错误消息。但是,如果您选择未来的日期并点击提交,则不会显示该消息。

这是我使用的资源: https://eincode.com/blogs/learn-how-to-validate-custom-input-components-with-react-hook-form

您还可以从 useForm 函数获得有关手表的更多信息: https://react-hook-form.com/api/useform/watch/


Fel*_*dor 6

尝试使用react-hook-form规则来添加验证

  <Controller
    name="currentName"
    control={control}
    render={({ field }) => (
      <TextField
        value={field.value}
        onChange={field.onChange}
        inputRef={field.ref}
        variant="outlined"
        size="small"
        fullWidth
        autoComplete="off"
        helperText={helperText}
      />
    )}
    rules={{
      validate: {
        required: (value) => {
          if (value === "SomeValue") return 'Some Message';
          if (!value) return '*Required';
        }
      },
      maxLength: 5
    }}
    defaultValue=""
  />
Run Code Online (Sandbox Code Playgroud)