[英]How to create custom validation from react hook form?
I want to create a custom validation starting from the validation below.我想从下面的验证开始创建一个自定义验证。 But I'm not successful so far.
但到目前为止我还没有成功。 I had visited this site and followed the codes in his "Custom validation rules" but I can't replicate it.
我访问过这个站点并遵循他的“自定义验证规则”中的代码,但我无法复制它。
The isBefore
method is working fine, but the validation does not. isBefore
方法工作正常,但验证没有。 And also how can we put a custom message with this custom validation?以及我们如何使用此自定义验证放置自定义消息?
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}
/>
)}
/>
Here is my attempt:这是我的尝试:
you need to use the hook useEffect and a controller.你需要使用钩子 useEffect 和一个控制器。 at the top of the page you need these two imports:
在页面顶部,您需要这两个导入:
import React, { useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
then you need the validation function this lives outside of the component.那么你需要这个位于组件之外的验证函数。
const isBefore = (date) => {
if (!date) {
return false;
}
const today = new Date();
today.setHours(0, 0, 0, 0);
return date > today;
};
The above function checks that the date you picked is in the future and not the past.上面的函数检查你选择的日期是在未来而不是过去。
Under your component you set everything to useForm在您的组件下,您将所有内容都设置为 useForm
const {
register,
handleSubmit,
control,
setValue,
watch,
errors,
setError,
clearError
} = useForm();
You then setup variables to watch for the datepicker to update, along with useEffect to watch for the change:然后设置变量以观察要更新的日期选择器,以及使用 useEffect 来观察更改:
const startDate = watch("startDate");
useEffect(() => {
register({ name: "startDate", type: "custom" }, { validate: { isBefore } });
});
You then define a handler inside of the component that handles the data change along with the validation.然后在组件内部定义一个处理程序,用于处理数据更改和验证。
const handleDateChange = (dateType) => (date) => {
if (!isBefore(date)) {
setError(dateType, "isBefore");
} else {
setError(dateType, "isBefore");
}
setValue(dateType, date);
alert(date);
};
the custom error message can exist anywhere in the form and you don't need to tie a ref to it.自定义错误消息可以存在于表单中的任何位置,您不需要将引用绑定到它。 the useForm() and watch('startDate') control the data for you.
useForm() 和 watch('startDate') 为您控制数据。
Here is the custom error message that can live anywhere within the form component.这是自定义错误消息,它可以存在于表单组件中的任何位置。
Please see updated codesandbox where I have the custom error message displayed near the submit button请查看更新的代码和框,其中我在提交按钮附近显示了自定义错误消息
{errors.startDate && (
<div variant="danger">
{errors.startDate.type === "isBefore" && (
<p>Please choose present or future date!</p>
)}
</div>
Here is a working codesandbox that I cleaned up a bit from yesterday, and added in some comments.这是一个有效的代码沙盒,我从昨天开始清理了一下,并添加了一些评论。 https://codesandbox.io/s/play-momentjs-forked-1hu4s?file=/src/index.js:1494-1802
https://codesandbox.io/s/play-momentjs-forked-1hu4s?file=/src/index.js:1494-1802
If you click the input and then choose a date in the past, and then click submit, the custom error message will show.如果单击输入然后选择过去的日期,然后单击提交,则会显示自定义错误消息。 However, if you select a date in the future and hit submit the message doesn't show.
但是,如果您选择将来的日期并点击提交,则不会显示该消息。
Here is a resource I used: https://eincode.com/blogs/learn-how-to-validate-custom-input-components-with-react-hook-form这是我使用的资源: https : //eincode.com/blogs/learn-how-to-validate-custom-input-components-with-react-hook-form
Also more information on watch that you get from useForm function: https://react-hook-form.com/api/useform/watch/您还可以从 useForm 函数获得有关 watch 的更多信息: https ://react-hook-form.com/api/useform/watch/
Try using rules of react-hook-form to add validations尝试使用 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=""
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.