'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.'
    and the errors object looks like this below.
{
 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. 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!



Solution 1:[1]

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. 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):

// ... 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>
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 José Alvarez