Skip to content

Instantly share code, notes, and snippets.

@edgarjaviertec
Created May 29, 2020 23:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edgarjaviertec/955eb47f02c012a8e3d118c0eb31c4d6 to your computer and use it in GitHub Desktop.
Save edgarjaviertec/955eb47f02c012a8e3d118c0eb31c4d6 to your computer and use it in GitHub Desktop.
Validar un formulario en React usando el hook de estado y la librería Yup
import React, {useState} from "react";
import * as Yup from "yup";
import InvalidFeedback from "../Components/InvalidFeedback";
export default function Login({login}) {
const [formValues, setFormValues] = useState({
'username': '',
'password': '',
});
const [touched, setTouched] = useState([]);
const [formErrors, setFormErrors] = useState({});
const [isSubmitting, setSubmitting] = useState(false);
let validationSchema = Yup.object().shape({
username: Yup.string().required("El usuario es requerido"),
password: Yup.string().required("La contraseña es requerida")
});
function handleBlur(event) {
if (!touched.includes(event.target.name)) {
setTouched([
...touched,
event.target.name
])
}
setFormErrors({});
validateForm();
}
function handleChange(event) {
setFormValues({
...formValues,
[event.target.name]: event.target.value
});
}
async function validateForm() {
let errores = {};
try {
const res = await validationSchema.validate(formValues, {abortEarly: false});
setFormValues(res);
} catch (e) {
e.inner.map(err => {
errores[err.path] = err.message;
});
const touchedErrors = Object.keys(errores)
.filter(key => touched.includes(key))
.reduce((acc, key) => {
if (!acc[key]) {
acc[key] = errores[key]
}
return acc
}, {});
setFormErrors(touchedErrors);
}
}
async function handleSubmit(e) {
e.preventDefault();
validateForm();
setSubmitting(true);
const noErrors = Object.keys(formErrors).length === 0;
if (noErrors) {
try {
await login(formValues.username, formValues.password)
} catch (error) {
console.log(error)
setSubmitting(false);
}
} else {
setSubmitting(false);
}
}
return (
<form onSubmit={handleSubmit}>
<div className="form-group">
<h1 className="mb-3 h3">
Inicie sesión
</h1>
<label htmlFor="username">
Nombre de usuario o correo
electrónico
</label>
<input
id="username"
name="username"
type="text"
className="form-control form-control-lg"
onChange={handleChange}
onBlur={handleBlur}
value={formValues.username}
/>
{formErrors.username ? <InvalidFeedback>{formErrors.username}</InvalidFeedback> : null}
</div>
<div className="form-group">
<label htmlFor="password">Contraseña</label>
<input
id="password"
name="password"
type="text"
className="form-control form-control-lg"
onChange={handleChange}
onBlur={handleBlur}
value={formValues.password}
/>
{formErrors.password ? <InvalidFeedback>{formErrors.password}</InvalidFeedback> : null}
</div>
<button disabled={isSubmitting}
className="btn btn-lg btn-success btn-block"
type="submit">Iniciar sesión
</button>
</form>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment