<Formik>
<Form>
{/* aquí va el resto del código */}
</Form>
</Formik>
<Formik
initialValues={{ email: "", password: "" }}
onSubmit={({ setSubmitting }) => {
console.log("Form is validated! Submitting the form...");
setSubmitting(false);
}}
>
{() => (
<Form>
<div className="form-group">
<label htmlFor="email">Email</label>
<Field
type="email"
name="email"
className="form-control"
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<Field
type="password"
name="password"
className="form-control"
/>
</div>
</Form>
)}
</Formik>
const SignupForm = () => {
const formik = useFormik({
initialValues: {
email: "",
},
onSubmit: (values) => {
console.log(JSON.stringify(values, null, 2));
},
});
return (
<form onSubmit={formik.handleSubmit}>
<label htmlFor="email">Email Address</label>
<input
id="email"
name="email"
type="email"
onChange={formik.handleChange}
value={formik.values.email}
/>
<button type="submit">Submit</button>
</form>
);
};
// Synchronous validation
const validate = (values, props) => {
const errors = {};
if (!values.email) {
errors.email = 'Required';
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = 'Invalid email address';
}
//...
return errors;
};
<Field
type="email"
name="email"
className={`form-control ${
touched.email && errors.email ? "is-invalid" : ""
}`}
/>
<ErrorMessage
component="div"
name="email"
className="invalid-feedback"
/>
npm install yup --save
import React from 'react';
import { Formik, Form, Field } from 'formik';
import * as Yup from 'yup';
const SignupSchema = Yup.object().shape({
firstName: Yup.string()
.min(2, 'Mínimo 2 letras')
.max(50, 'Máximo 50 letras')
.required('Campo obligatorio'),
lastName: Yup.string()
.min(2, 'Mínimo 2 letras')
.max(50, 'Máximo 50 letras')
.required('Campo obligatorio'),
email: Yup.string().email('Email no válido').required('Campo obligatorio'),
});
export const ValidationSchemaExample = () => (
<div>
<h1>Registro</h1>
<Formik
initialValues={{
firstName: '',
lastName: '',
email: '',
}}
validationSchema={SignupSchema}
onSubmit={ (values) => {
console.log(values);
}}
>
{({ errors, touched }) => (
<Form>
<Field name="firstName" />
{errors.firstName && touched.firstName ? (
<div>{errors.firstName}</div>
) : null}
<Field name="lastName" />
{errors.lastName && touched.lastName ? (
<div>{errors.lastName}</div>
) : null}
<Field name="email" type="email" />
{errors.email && touched.email ? <div>{errors.email}</div> : null}
<button type="submit">Submit</button>
</Form>
)}
</Formik>
</div>
);
<Formik
initialValues={{ username: "", email: "", password: "" }}
// . . .
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
console.log(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 400);
}}
>