add optional regex validation to TextEntry component

This commit is contained in:
Josh Hawkins 2025-05-17 11:06:40 -05:00
parent 54a5084940
commit 4652f0d94d

View File

@ -18,18 +18,33 @@ type TextEntryProps = {
allowEmpty?: boolean; allowEmpty?: boolean;
onSave: (text: string) => void; onSave: (text: string) => void;
children?: React.ReactNode; children?: React.ReactNode;
regexPattern?: RegExp;
regexErrorMessage?: string;
}; };
export default function TextEntry({ export default function TextEntry({
defaultValue = "", defaultValue = "",
placeholder, placeholder,
allowEmpty = false, allowEmpty = false,
onSave, onSave,
children, children,
regexPattern,
regexErrorMessage = "Input does not match the required format",
}: TextEntryProps) { }: TextEntryProps) {
const formSchema = z.object({ const formSchema = z.object({
text: allowEmpty text: z
? z.string().optional() .string()
: z.string().min(1, "Field is required"), .optional()
.refine(
(val) => {
if (!allowEmpty && !val) return false;
if (val && regexPattern) return regexPattern.test(val);
return true;
},
{
message: regexPattern ? regexErrorMessage : "Field is required",
},
),
}); });
const form = useForm<z.infer<typeof formSchema>>({ const form = useForm<z.infer<typeof formSchema>>({