Hello friends, welcome back to my blog. Today in this blog post, I am going to show you, Building Forms in React with Formik + Validations.
Guys in this working demo I have used latest react version + formik module + bootstrap 5 library.
For React and bootstrap 5 new comers, please check the below link:
Friends now I proceed onwards and here is the working code snippet for react ecommerce template free and please use this carefully to avoid the mistakes:
1. Firstly, we need fresh reactjs setup and for that, we need to run below commands into out terminal and also we should have latest node version installed on our system:
npx create-react-app reactdemo cd reactdemo npm install formik --save
2. Finally for the main output, we need to add below code into our reactdemo/src/App.js file:
guys to use bootstrap 5 in reactjs application please see this tutorial : add bootstrap 5 in react
import React from "react"; import { Formik, Form, Field } from "formik"; function validateEmail(value) { let error; if (!value) { error = 'Required'; } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) { error = 'Invalid email address'; } return error; } function validateUsername(value) { let error; if (!value) { error = 'Required'; } return error; } export const FieldLevelValidationExample = () => ( <div> <h3 className="mb-3">Signup</h3> <Formik initialValues={{ username: '', email: '', }} onSubmit={values => { // same shape as initial values console.log(values); }} > {({ errors, touched, validateField, validateForm }) => ( <Form> <div className="mb-3"> <label className="form-label">Email address</label> <Field className="form-control" name="email" validate={validateEmail} /> {errors.email && touched.email && <div className="pt-1 text-danger" >{errors.email}</div>} </div> <div className="mb-3"> <label className="form-label">Username</label> <Field className="form-control" name="username" validate={validateUsername} /> {errors.username && touched.username && <div className="pt-1 text-danger">{errors.username}</div>} </div> <button className="btn btn-primary" type="submit">Submit</button> </Form> )} </Formik> </div> ); function App() { return ( <div className="App container p-5"> <FieldLevelValidationExample/> </div> ); } export default App;
Friends in the end must run npm start command into your terminal to run the react project.
Now we are done friends. If you have any kind of query, suggestion and new requirement then feel free to comment below.
Note: Friends, In this post, I just tell the basic setup and things, you can change the code according to your requirements.
I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad because with your views, I will make my next posts more good and helpful.
Jassa
Thanks
Recent Comments