[英]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"
/>
validateNickname
function returns error) Then, error message is registered 'Invalid nickname.'validateNickname
function 返回错误)然后,错误消息被注册为“无效的昵称”。{
nickname:
message: "Invalid nickname."
ref:...
type: "validate"
}
but the problem is但问题是
{
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.