Skip to content

issue: Focus interactions with native validation #846

@alexandre-gille

Description

@alexandre-gille

Version Number

7.62.0

Codesandbox/Expo snack

https://codesandbox.io/p/sandbox/dreamy-fire-jfv93z

Steps to reproduce

Submit the form once : native validation messages won't show.
They'll appear properly on subsequent validations.

I suspect flawed interactions while setting focus, dismissing native validation popups instantly.
It seems to be the case (or at least related), as the problem do not occur if you set shouldFocusError to false (the errors are still focused/scrolledIntoView anyway, but this time on the last instead of the first) or if there's only one field in the form.

However, this workaround still introduce some inconsistencies between the first validation and the following ones. The first one will focus the last registered input, but the others will focus the first registered input.
And in some circonstances with this setting it can lead to some misleading behaviour where the browser is focusing and scrolling to an invalid input while showing the validation message of another invalid one (based on register order/declaration order in the associated validation schema).

import * as React from "react";
import { useForm } from "react-hook-form";
import Headers from "./Header";
import "./styles.css";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";

let renderCount = 0;

const schema = z.object({
  firstName: z
    .string()
    .trim()
    .min(1, { error: "Det här fältet är obligatoriskt." }),
  lastName: z
    .string()
    .trim()
    .min(1, { error: "Det här fältet är obligatoriskt." }),
});

export default function App() {
  const { register, handleSubmit } = useForm({
    shouldUseNativeValidation: true,
    resolver: zodResolver(schema),
  });
  const onSubmit = (data) => console.log(data);
  renderCount++;

  return (
    <div>
      <Headers
        renderCount={renderCount}
        description="Performant, flexible and extensible forms with easy-to-use validation."
      />

      <form onSubmit={handleSubmit(onSubmit)}>
        <input {...register("firstName")} placeholder="First Name" />
        <input {...register("lastName")} placeholder="Last Name" />
        <input type="submit" />
      </form>
    </div>
  );
}

Expected behaviour

Native validation messages should appear even on the very first validation call.

What browsers are you seeing the problem on?

Chrome, Firefox

Relevant log output

Code of Conduct

  • I agree to follow this project's Code of Conduct

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions