Last active
April 7, 2022 04:16
-
-
Save Manntrix/b6b56c68b251997323d9b5eb7586c73a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "./App.css"; | |
import { Formik } from "formik"; | |
import * as Yup from "yup"; | |
// Creating schema | |
const schema = Yup.object().shape({ | |
email: Yup.string() | |
.required("Email is a required field") | |
.email("Invalid email format"), | |
password: Yup.string() | |
.required("Password is a required field") | |
.min(8, "Password must be at least 8 characters"), | |
}); | |
function App() { | |
return ( | |
<> | |
{/* Wrapping form inside formik tag and passing our schema to validationSchema prop */} | |
<Formik | |
validationSchema={schema} | |
initialValues={{ email: "", password: "" }} | |
onSubmit={(values) => { | |
// Alert the input values of the form that we filled | |
alert(JSON.stringify(values)); | |
}} | |
> | |
{({ | |
values, | |
errors, | |
touched, | |
handleChange, | |
handleBlur, | |
handleSubmit, | |
}) => ( | |
<div className="login"> | |
<div className="form"> | |
{/* Passing handleSubmit parameter tohtml form onSubmit property */} | |
<form noValidate onSubmit={handleSubmit}> | |
<span>Login</span> | |
{/* Our input html with passing formik parameters like handleChange, values, handleBlur to input properties */} | |
<input | |
type="email" | |
name="email" | |
onChange={handleChange} | |
onBlur={handleBlur} | |
value={values.email} | |
placeholder="Enter email id / username" | |
className="form-control inp_text" | |
id="email" | |
/> | |
{/* If validation is not passed show errors */} | |
<p className="error"> | |
{errors.email && touched.email && errors.email} | |
</p> | |
{/* Our input html with passing formik parameters like handleChange, values, handleBlur to input properties */} | |
<input | |
type="password" | |
name="password" | |
onChange={handleChange} | |
onBlur={handleBlur} | |
value={values.password} | |
placeholder="Enter password" | |
className="form-control" | |
/> | |
{/* If validation is not passed show errors */} | |
<p className="error"> | |
{errors.password && touched.password && errors.password} | |
</p> | |
{/* Click on submit button to submit the form */} | |
<button type="submit">Login</button> | |
</form> | |
</div> | |
</div> | |
)} | |
</Formik> | |
</> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment