mirror of
https://github.com/blakeblackshear/frigate.git
synced 2025-12-06 13:34:13 +03:00
Form validation tweaks (#20790)
* ensure id field is expanded on form errors * only validate id field when name field has no errors * use ref instead * all numeric is an invalid name
This commit is contained in:
parent
2e288109f4
commit
e7394d0dc1
@ -8,7 +8,7 @@ import {
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { useFormContext } from "react-hook-form";
|
||||
import { generateFixedHash, isValidId } from "@/utils/stringUtil";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@ -41,8 +41,9 @@ export default function NameAndIdFields<T extends FieldValues = FieldValues>({
|
||||
placeholderId,
|
||||
}: NameAndIdFieldsProps<T>) {
|
||||
const { t } = useTranslation(["common"]);
|
||||
const { watch, setValue, trigger } = useFormContext<T>();
|
||||
const { watch, setValue, trigger, formState } = useFormContext<T>();
|
||||
const [isIdVisible, setIsIdVisible] = useState(false);
|
||||
const hasUserTypedRef = useRef(false);
|
||||
|
||||
const defaultProcessId = (name: string) => {
|
||||
const normalized = name.replace(/\s+/g, "_").toLowerCase();
|
||||
@ -58,6 +59,7 @@ export default function NameAndIdFields<T extends FieldValues = FieldValues>({
|
||||
useEffect(() => {
|
||||
const subscription = watch((value, { name }) => {
|
||||
if (name === nameField) {
|
||||
hasUserTypedRef.current = true;
|
||||
const processedId = effectiveProcessId(value[nameField] || "");
|
||||
setValue(idField, processedId as PathValue<T, Path<T>>);
|
||||
trigger(idField);
|
||||
@ -66,6 +68,14 @@ export default function NameAndIdFields<T extends FieldValues = FieldValues>({
|
||||
return () => subscription.unsubscribe();
|
||||
}, [watch, setValue, trigger, nameField, idField, effectiveProcessId]);
|
||||
|
||||
// Auto-expand if there's an error on the ID field after user has typed
|
||||
useEffect(() => {
|
||||
const idError = formState.errors[idField];
|
||||
if (idError && hasUserTypedRef.current && !isIdVisible) {
|
||||
setIsIdVisible(true);
|
||||
}
|
||||
}, [formState.errors, idField, isIdVisible]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<FormField
|
||||
|
||||
@ -43,5 +43,5 @@ export function generateFixedHash(name: string, prefix: string = "id"): string {
|
||||
* @returns True if the name is valid, false otherwise
|
||||
*/
|
||||
export function isValidId(name: string): boolean {
|
||||
return /^[a-zA-Z0-9_-]+$/.test(name);
|
||||
return /^[a-zA-Z0-9_-]+$/.test(name) && !/^\d+$/.test(name);
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user