useformik

Solutions on MaxInterview for useformik by the best coders in the world

showing results for - "useformik"
Elle
28 Nov 2017
1// useFormik form 
2import { useFormik } from "formik";
3
4const Useformik = () => {
5  const initialValues = {
6    name: "",
7    email: "",
8    age: "",
9  };
10  const onSubmit = (values) => {
11    alert(JSON.stringify(values, null, 2));
12  };
13  const validate = (values) => {
14    console.log("~ values", values);
15    let errors = {};
16    if (!values.name) {
17      errors.name = "Required";
18      console.log("no name ");
19    }
20    if (!values.email) {
21      errors.email = "Required";
22    } else if (
23      !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)
24    ) {
25      errors.email = "Invalid email address";
26    }
27    if (!values.age) {
28      errors.age = "Required";
29    }
30    return errors;
31  };
32  const formik = useFormik({
33    initialValues,
34    onSubmit,
35    validate,
36  });
37  console.log("~ visite", formik.touched);
38
39  return (
40    <>
41      <h1>Form useformik</h1>
42      <form onSubmit={formik.handleSubmit} className="box-wrapper">
43        <div className="container">
44          <div className="row">
45            {/* <div className="form-control"> */}
46            <label>Name</label>
47            <input
48              name="name"
49              type="text"
50              onChange={formik.handleChange}
51              value={formik.values.name}
52              onBlur={formik.handleBlur}
53            />
54            {formik.touched.name && formik.errors.name ? (
55              <div className="error">{formik.errors.name}</div>
56            ) : null}
57            <br />
58            <label>Email</label>
59            <input
60              name="email"
61              type="text"
62              onChange={formik.handleChange}
63              value={formik.values.email}
64              onBlur={formik.handleBlur}
65            />
66            {formik.touched.email && formik.errors.email ? (
67              <div className="error">{formik.errors.email}</div>
68            ) : null}
69            <br />
70            <label>Age</label>
71            <input
72              name="age"
73              type="number"
74              onChange={formik.handleChange}
75              value={formik.values.age}
76              onBlur={formik.handleBlur}
77            />
78            {formik.touched.age && formik.errors.age ? (
79              <div className="error">{formik.errors.age}</div>
80            ) : null}
81            <br />
82          </div>
83        </div>
84
85        <button type="submit" className="btn btn-primary">
86          Submit
87        </button>
88      </form>
89    </>
90  );
91};
92
93export default Useformik;