From feb896d96b47fde2262a225fb8d5c623a439dcd6 Mon Sep 17 00:00:00 2001 From: llauderesv Date: Tue, 5 May 2020 11:28:35 +0800 Subject: [PATCH] add new function setValidatorSchema to be able to set a new validation state #7 --- src/example/Form/index.js | 4 ---- src/lib/index.js | 15 +++++++++++++-- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/example/Form/index.js b/src/example/Form/index.js index 88f383b..122c000 100644 --- a/src/example/Form/index.js +++ b/src/example/Form/index.js @@ -10,8 +10,6 @@ function Form() { tags: { value: '', error: '' }, }; - const delay = () => new Promise((resolve) => setTimeout(resolve, 3000)); - // Create your own validationStateSchema // stateSchema property should be the same in validationStateSchema // in-order a validation to works in your input. @@ -49,8 +47,6 @@ function Form() { dirty, handleOnChange, handleOnSubmit, - setFieldError, - setFieldValue, setStateSchema, disable, } = useForm(stateSchema, stateValidatorSchema, onSubmitForm); diff --git a/src/lib/index.js b/src/lib/index.js index 91683cd..451d34e 100644 --- a/src/lib/index.js +++ b/src/lib/index.js @@ -14,6 +14,7 @@ function useForm( submitFormCallback ) { const [state, setStateSchema] = useState(stateSchema); + const [validatorSchema, setValidatorSchema] = useState(stateValidatorSchema); const [values, setValues] = useState(get_prop_values(state, VALUE)); const [errors, setErrors] = useState(get_prop_values(state, ERROR)); @@ -45,6 +46,15 @@ function useForm( setErrors(errors); }, [state]); // eslint-disable-line + useEffect(() => { + const errors = Object.keys(values).reduce((accu, curr) => { + accu[curr] = validateField(curr, values[curr]); + return accu; + }, {}); + + setErrors(errors); + }, [validatorSchema]); // eslint-disable-line + // For every changed in our state this will be fired // To be able to disable the button useEffect(() => { @@ -67,7 +77,7 @@ function useForm( // Function used to validate form fields const validateField = useCallback( (name, value) => { - const fieldValidator = stateValidatorSchema[name]; + const fieldValidator = validatorSchema[name]; // Making sure that stateValidatorSchema name is same in // stateSchema if (!fieldValidator) { @@ -93,7 +103,7 @@ function useForm( return error; }, - [stateValidatorSchema, values] + [validatorSchema, values] ); // Set Initial Error State @@ -148,6 +158,7 @@ function useForm( errors, disable, setStateSchema, + setValidatorSchema, setFieldValue, setFieldError, handleOnChange,