Blog>
Snippets

Error Handling and Display in Form Fields

Show how to handle and display validation errors for form fields, including custom error messages from asynchronous validation.
const { register, handleSubmit, formState: { errors } } = useForm();
Initialize the form with useForm hook, including form state to track errors.
const onSubmit = data => console.log(data);
Define a submit function to handle form submission.
const emailExistsValidator = async (value) => {\n  const exists = await checkEmailExists(value);\n  return exists ? 'Email already in use.' : undefined;\n};
Asynchronous validation function to check if email exists. Returns an error message if true.
// In the form rendering\n<form onSubmit={handleSubmit(onSubmit)}>\n  <input name="email" {...register('email', {\n    required: 'Email is required.',\n    validate: emailExistsValidator\n  })} />\n  {errors.email && <span>{errors.email.message}</span>}\n  <button type="submit">Submit</button>\n</form>
Form rendering with email field. Includes registration for the email input with required validation and asynchronous email existence check. Also displays any validation error messages.