Skip to content

Commit 5832a6c

Browse files
committed
feat: enhance useForm validation logic with isValid method and improved validation function
1 parent ae460b2 commit 5832a6c

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

src/components/form/useForm.ts

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import {useCallback, useMemo, useState} from "react";
44

55
export type Validations<Values> = Partial<{
6-
[Key in keyof Values]: (value: Values[Key]) => string | null;
6+
[Key in keyof Values]: (value: Values[Key], values?: Values) => string | null;
77
}>
88

99
export interface FormValidationProps<Values> {
@@ -30,6 +30,7 @@ export type FormValidationReturn<Values> = [IValidation<Values>, () => void]
3030

3131
export interface IValidation<Values> {
3232
getInputProps<Key extends keyof Values>(key: Key): ValidationProps<Values[Key]>
33+
isValid(): boolean
3334
}
3435

3536
class Validation<Values> implements IValidation<Values> {
@@ -46,12 +47,25 @@ class Validation<Values> implements IValidation<Values> {
4647
this.initialRender = initial
4748
}
4849

49-
public getInputProps<Key extends keyof Values>(key: Key): ValidationProps<Values[Key]> {
50+
isValid(): boolean {
51+
if (!this.currentValidations) return true
52+
for (const key in this.currentValidations) {
53+
const validateFn = this.currentValidations[key]
54+
if (validateFn) {
55+
const message = validateFn(this.currentValues[key], this.currentValues)
56+
if (message !== null) return false
57+
}
58+
}
59+
60+
return true
61+
}
62+
63+
getInputProps<Key extends keyof Values>(key: Key): ValidationProps<Values[Key]> {
5064

5165
const currentValue = ((this.currentValues[key]) || null)!!
5266
const currentName = key as string
5367
const currentFc = !!this.currentValidations && !!this.currentValidations[key] ? this.currentValidations[key] : (value: typeof currentValue) => null
54-
const message = !this.initialRender ? currentFc(currentValue) : null
68+
const message = !this.initialRender ? currentFc(currentValue, this.currentValues) : null
5569

5670
return {
5771
initialValue: currentValue,
@@ -87,7 +101,7 @@ export const useForm = <Values extends Record<string, any> = Record<string, any>
87101
let inputProps: IValidation<Values> = new Validation(changeValue, values, validate, false)
88102

89103
setInputProps(() => inputProps)
90-
if (onSubmit) onSubmit(values as Values)
104+
if (onSubmit && inputProps.isValid()) onSubmit(values as Values)
91105

92106
}, [])
93107

0 commit comments

Comments
 (0)