如何在React Hook Form中组合最小和最大验证错误?

huangapple go评论71阅读模式
英文:

How can I combine min and max validation errors in React Hook Form?

问题

{errors.subject?.type === "required" && (
  <p className="text-error" role="alert">
    Subject is required
  </p>
)}
{errors.subject?.type === "minLength" && (
  <p className="text-error" role="alert">
    minLength 2
  </p>
)}
{errors.subject?.type === "maxLength" && (
  <p className="text-error" role="alert">
    maxLength 50 characters
  </p>
)}
英文:
 

 &lt;input
            {...register(&quot;subject&quot;, {
              maxLength: 50,
              minLength: 2,
              required: true,
            })}
            disabled={isLoading}
            id=&quot;subject&quot;
            autoComplete=&quot;on&quot;
            type=&quot;text&quot;
            placeholder=&quot;Subject&quot;
            className={`w-full ${errors.subject ? &quot;outline-error&quot; : &quot;&quot;}`}
          /&gt;
          {errors.subject?.type === &quot;maxLength&quot; &amp;&amp; (
            &lt;p className=&quot;text-error&quot; role=&quot;alert&quot;&gt;
              maxLength 50 characters
            &lt;/p&gt;
          )}
          {errors.subject?.type === &quot;minLength&quot; &amp;&amp; (
            &lt;p className=&quot;text-error&quot; role=&quot;alert&quot;&gt;
              minLength 2
            &lt;/p&gt;
          )}
          {errors.subject?.type === &quot;required&quot; &amp;&amp; (
            &lt;p className=&quot;text-error&quot; role=&quot;alert&quot;&gt;
              Subject is required
            &lt;/p&gt;
          )}

I want the min and max errors to be combined... when I try to combine it doesn't work as I wanted. It sometimes show both error or or does't show error . I want when user empty the field the required error should show and when user enter something in the field if it does not match the min and max length the min max error show

答案1

得分: 1

你在这方面做得很详细,就像是为每一个需求都创建了不同的 span。与其这样做,你可以这样:

首先,在 react-hook-form 中,从 useForm() 中获取 formState: { errors } 属性,像这样:

const { register, handleSubmit, reset, setValue, formState: { errors }, clearErrors } = useForm();

还要像这样导入 React-hook-form 中的 ErrorMessage 组件:

import { ErrorMessage } from "@hookform/error-message";

然后,你可以在需要的地方在输入框后面应用 ErrorMessage 组件,就像这样:

<input type="text" className="form-control" 
    {...register("subject", {
        required: "* 输入主题",
        minLength: {
            value: 2,
            message: "至少需要2个字符"
        },
        maxLength: {
            value: 50,
            message: "最多允许50个字符"
        }
    })} />
<ErrorMessage errors={errors} name="subject" 
    render={({ message }) => (
        <span className="errorMessage">{message}</span>
    )}
/>

在这里,你可以提供任何自定义消息,并且之后可以在 ErrorMessage 组件中解构它。
谢谢...!

英文:

You are going very long in this like you are making different different span for each and every requirement.
Instead of that you can do like this.

First take formState: { errors } attribute from useForm() in react-hook-form like this,

const { register, handleSubmit, reset, setValue, formState: { errors }, clearErrors } = useForm();

also import ErrorMessage Component from React-hook-form like this,

import { ErrorMessage } from &quot;@hookform/error-message&quot;;

Then you can apply ErrorMessage component after input whenever you want like this...

&lt;input type=&quot;text&quot; className=&quot;form-control&quot; 
    {...register(&quot;subject&quot;, {required : &quot;* Enter subject &quot;, 
                minLength:{
                value:2,
                message: &quot;Minimum 2 Characters required&quot;
                }, 
                maxLength: {
                value:50,
                message: &quot;Max 50 is allowed&quot;
                }
                } )}  /&gt;
  &lt;ErrorMessage errors={errors} name=&quot;subject&quot; 
                render={({message}) =&gt; (
          &lt;span className=&quot;errorMessage&quot; &gt;{message}&lt;/span&gt;
        )}
     /&gt;

Here you can give any custom message you want, and after you can de-structure in ErrorMessage component.
Thank you...!

huangapple
  • 本文由 发表于 2023年5月25日 20:17:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76332183.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定