From 5832a6c1a4e51323fe75adbf19e1fd81ac7d07f6 Mon Sep 17 00:00:00 2001 From: nicosammito Date: Fri, 14 Nov 2025 12:58:58 +0100 Subject: [PATCH] feat: enhance useForm validation logic with isValid method and improved validation function --- src/components/form/useForm.ts | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/components/form/useForm.ts b/src/components/form/useForm.ts index 03c5b029..50e4514a 100644 --- a/src/components/form/useForm.ts +++ b/src/components/form/useForm.ts @@ -3,7 +3,7 @@ import {useCallback, useMemo, useState} from "react"; export type Validations = Partial<{ - [Key in keyof Values]: (value: Values[Key]) => string | null; + [Key in keyof Values]: (value: Values[Key], values?: Values) => string | null; }> export interface FormValidationProps { @@ -30,6 +30,7 @@ export type FormValidationReturn = [IValidation, () => void] export interface IValidation { getInputProps(key: Key): ValidationProps + isValid(): boolean } class Validation implements IValidation { @@ -46,12 +47,25 @@ class Validation implements IValidation { this.initialRender = initial } - public getInputProps(key: Key): ValidationProps { + isValid(): boolean { + if (!this.currentValidations) return true + for (const key in this.currentValidations) { + const validateFn = this.currentValidations[key] + if (validateFn) { + const message = validateFn(this.currentValues[key], this.currentValues) + if (message !== null) return false + } + } + + return true + } + + getInputProps(key: Key): ValidationProps { const currentValue = ((this.currentValues[key]) || null)!! const currentName = key as string const currentFc = !!this.currentValidations && !!this.currentValidations[key] ? this.currentValidations[key] : (value: typeof currentValue) => null - const message = !this.initialRender ? currentFc(currentValue) : null + const message = !this.initialRender ? currentFc(currentValue, this.currentValues) : null return { initialValue: currentValue, @@ -87,7 +101,7 @@ export const useForm = = Record let inputProps: IValidation = new Validation(changeValue, values, validate, false) setInputProps(() => inputProps) - if (onSubmit) onSubmit(values as Values) + if (onSubmit && inputProps.isValid()) onSubmit(values as Values) }, [])