Skip to content

Instantly share code, notes, and snippets.

@Klerith
Created June 6, 2022 19:58
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save Klerith/09dede50a8a397231744d4545b771408 to your computer and use it in GitHub Desktop.
Save Klerith/09dede50a8a397231744d4545b771408 to your computer and use it in GitHub Desktop.
useForm con Validaciones
import { useEffect, useMemo, useState } from 'react';
export const useForm = ( initialForm = {}, formValidations = {}) => {
const [ formState, setFormState ] = useState( initialForm );
const [ formValidation, setFormValidation ] = useState({});
useEffect(() => {
createValidators();
}, [ formState ])
useEffect(() => {
setFormState( initialForm );
}, [ initialForm ])
const isFormValid = useMemo( () => {
for (const formValue of Object.keys( formValidation )) {
if ( formValidation[formValue] !== null ) return false;
}
return true;
}, [ formValidation ])
const onInputChange = ({ target }) => {
const { name, value } = target;
setFormState({
...formState,
[ name ]: value
});
}
const onResetForm = () => {
setFormState( initialForm );
}
const createValidators = () => {
const formCheckedValues = {};
for (const formField of Object.keys( formValidations )) {
const [ fn, errorMessage ] = formValidations[formField];
formCheckedValues[`${ formField }Valid`] = fn( formState[formField] ) ? null : errorMessage;
}
setFormValidation( formCheckedValues );
}
return {
...formState,
formState,
onInputChange,
onResetForm,
...formValidation,
isFormValid
}
}
@devdnia
Copy link

devdnia commented Jul 5, 2022

Muchas gracias!!! eres super cuidadoso y no das nada por hecho y eso es genial!!!

@josantos-devos
Copy link

Super, muchas gracias maestro!

@DiegoIza27
Copy link

gracias profe

@emersonxinay
Copy link

eres un crack y bien ordenado, se aprende mucho de tu orden.

@MOLINA123
Copy link

Profeeeeee, sin duda alguna eres el mejor, con todos lo cursos que he realizado contigo; estoy creando un proyecto. Cuando lo termine y lo ponga en pruducción, pues veré como lo posteo en tus redes, agradeciendo todos tus conocimientos impartido en cada clase de tus cursos...

@CJ-arg
Copy link

CJ-arg commented Aug 29, 2023

gracias muy buen curso

@julioemc2
Copy link

Genial, tienes cuidado de todos los detalles, y si no los escribes, los comentas igual. Tambien creando un proyecto con lo aprendido aqui.

@Junior009k
Copy link

Muchas gracias desde Republica Dominicana, se aprende mucho y me ha dadoo mas seguridad a la hora de trabajar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment