Skip to content

Commit dc38875

Browse files
committed
fix: focus-on-first-error-field-when-shouldUseNativeValidation
1 parent 2e9bc7c commit dc38875

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

src/validateFieldsNatively.ts

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,18 @@ const setCustomValidity = (
1111
ref: Ref,
1212
fieldPath: string,
1313
errors: FieldErrors,
14+
shouldReport: boolean = true,
1415
) => {
1516
if (ref && 'reportValidity' in ref) {
1617
const error = get(errors, fieldPath) as FieldError | undefined;
1718
ref.setCustomValidity((error && error.message) || '');
1819

19-
ref.reportValidity();
20+
if (shouldReport) {
21+
if ('focus' in ref && typeof (ref as any).focus === 'function') {
22+
(ref as any).focus();
23+
}
24+
ref.reportValidity();
25+
}
2026
}
2127
};
2228

@@ -27,12 +33,35 @@ export const validateFieldsNatively = <TFieldValues extends FieldValues>(
2733
): void => {
2834
for (const fieldPath in options.fields) {
2935
const field = options.fields[fieldPath];
36+
3037
if (field && field.ref && 'reportValidity' in field.ref) {
31-
setCustomValidity(field.ref, fieldPath, errors);
38+
setCustomValidity(field.ref, fieldPath, errors, false);
3239
} else if (field && field.refs) {
3340
field.refs.forEach((ref: HTMLInputElement) =>
34-
setCustomValidity(ref, fieldPath, errors),
41+
setCustomValidity(ref, fieldPath, errors, false),
3542
);
3643
}
3744
}
45+
46+
const ordered = Array.isArray((options as any).names)
47+
? ((options as any).names as string[])
48+
: Object.keys(options.fields);
49+
50+
const firstErrorPath = ordered.find((name) => Boolean(get(errors, name)));
51+
if (!firstErrorPath) {
52+
return;
53+
}
54+
55+
const firstField = options.fields[firstErrorPath];
56+
const firstRef: Ref | undefined =
57+
firstField?.ref ??
58+
(Array.isArray((firstField as any)?.refs)
59+
? (firstField as any).refs[0]
60+
: undefined);
61+
62+
if (!firstRef) {
63+
return;
64+
}
65+
66+
setCustomValidity(firstRef, firstErrorPath, errors, true);
3867
};

0 commit comments

Comments
 (0)