简体   繁体   English

react-hook-form 的验证 function 总是返回错误

[英]react-hook-form's validate function always returns errors

This is the one that occurs problem.这是发生问题的一个。

 <input
     type="text"
     name="nickname"
     {...register('nickname', {
     required: true,
     validate: async (value) =>
        value !== profile?.nickname &&
        (await validateNickname(value).catch(() => {
         return 'Invalid nickname.';
        })),
     })}
     placeholder="Nickname"
     />
  • If the input value is not same with the defaultValue如果输入值与默认值不同
  • and It's duplicated with another nickname, ( validateNickname function returns error) Then, error message is registered 'Invalid nickname.'并且它与另一个昵称重复,( validateNickname function 返回错误)然后,错误消息被注册为“无效的昵称”。
    and the errors object looks like this below.错误 object 如下所示。
{
 nickname:
 message: "Invalid nickname."
 ref:...
 type: "validate"
}

but the problem is但问题是

  • If I input the value which is same with the defaultValue,如果我输入与默认值相同的值,
  • or If I input not duplicated value, The errors object should be empty.或者如果我输入不重复的值,错误 object 应该是空的。 but it still returns error like this below.但它仍然返回如下错误。
{
 nickname:
 message: ""
 ref:...
 type: "validate"
}

so there's no error message registered, but somehow, error is exist.所以没有注册错误消息,但不知何故,错误存在。
Please let me know if there's anything I'm doing wrong.如果我做错了什么,请告诉我。 Thanks!谢谢!

This could be the problem:这可能是问题所在:

(await validateNickname(value).catch(() => {
         return 'Invalid nickname.';
        }))

You want to return a boolean in your AND expression, but you are returning a string, which would be saying the validation is correct.您想要在 AND 表达式中返回 boolean,但您返回的是一个字符串,表示验证正确。 If you want to handle that validation error so as to display the message in html you can do a simple error handling approach like this one (using named validations):如果您想处理该验证错误以便在 html 中显示消息,您可以执行一种简单的错误处理方法,例如这个(使用命名验证):

// ... your validation set up
validate:{
    validateNickname_ : async (value) => {
        let response = false;
        await validateNickname(value)
            .then( () => { response = true;})
            .catch(() => { response = false;});
        return value !== profile?.nickname && response;
    }
}

// ... showing your error message
{
    errors.nickname && errors.nickname.type=="validateNickname_" &&
    <p className='error-form-msg'>
    {"Your custom error message here ..."}
    </p>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM