In this tutorial, I will show you how to implement React Form Validation with Formik, Yup, axios and bootstap also after validated the form by submiting the form the data will save to database using mysql and php
Formik : https://formik.org/
Yup : https://www.npmjs.com/package/yup
Bootstrap : https://react-bootstrap.github.io/getting-started/introduction/
Axios : https://github.com/axios/axios
Install Formik
npm install formik yup
C:\reactdev\myreactdev>npm install formik yup
https://github.com/axios/axios
Installing the Axios Client
$ npm install axios
C:\reactdev\myreactdev>npm install axios
Install bootstrap
npm install react-bootstrap bootstrap@5.1.3
C:\reactdev\myreactdev>npm install react-bootstrap bootstrap@5.1.3
https://react-bootstrap.github.io/getting-started/introduction/
//src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import 'bootstrap/dist/css/bootstrap.min.css'; ReactDOM.render( <App />, document.getElementById('root') )public/index.html
//public/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>ReactJS </title> </head> <body> <div id="root"></div> </body> </html>src/App.js
//src/App.js import React from 'react'; import { Formik, Field, Form, ErrorMessage } from 'formik'; import * as Yup from 'yup'; import axios from 'axios'; class App extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(data) { console.log(JSON.stringify(data, null, 2)); let formData = new FormData(); formData.append('fullname', data.fullname) formData.append('username', data.username) formData.append('email', data.email) formData.append('password', data.password) axios({ method: 'post', url: 'http://localhost/devtest/reactjs/reg.php/', data: formData, config: { headers: {'Content-Type': 'multipart/form-data' }} }) .then(function (response) { //handle success console.log(response) alert('New User Successfully Added.'); }) .catch(function (response) { //handle error console.log(response) }); } validationSchema() { return Yup.object().shape({ fullname: Yup.string().required('Fullname is required'), username: Yup.string() .required('Username is required') .min(6, 'Username must be at least 6 characters') .max(20, 'Username must not exceed 20 characters'), email: Yup.string() .required('Email is required') .email('Email is invalid'), password: Yup.string() .required('Password is required') .min(6, 'Password must be at least 6 characters') .max(40, 'Password must not exceed 40 characters'), confirmPassword: Yup.string() .required('Confirm Password is required') .oneOf([Yup.ref('password'), null], 'Confirm Password does not match'), acceptTerms: Yup.bool().oneOf([true], 'Accept Terms is required'), }); } render() { const initialValues = { fullname: '', username: '', email: '', password: '', confirmPassword: '', acceptTerms: false, }; return ( <div className="container" style={{padding: 20}}> <div className="register-form"><h1>ReactJS Axios PHP Mysql Form Validation with Formik and Yup</h1> <Formik initialValues={initialValues} validationSchema={this.validationSchema} onSubmit={this.handleSubmit}> {({ resetForm }) => ( <Form> <div className="form-group"> <label>Full Name</label> <Field name="fullname" type="text" className="form-control"/> <ErrorMessage name="fullname" component="div" className="text-danger"/> </div> <div className="form-group"> <label htmlFor="username"> Username </label> <Field name="username" type="text" className="form-control" /> <ErrorMessage name="username" component="div" className="text-danger"/> </div> <div className="form-group"> <label htmlFor="email"> Email </label> <Field name="email" type="email" className="form-control" /> <ErrorMessage name="email" component="div" className="text-danger"/> </div> <div className="form-group"> <label htmlFor="password"> Password </label> <Field name="password" type="password" className="form-control"/> <ErrorMessage name="password" component="div" className="text-danger"/> </div> <div className="form-group"> <label htmlFor="confirmPassword"> Confirm Password </label> <Field name="confirmPassword" type="password" className="form-control"/> <ErrorMessage name="confirmPassword" component="div" className="text-danger"/> </div> <div className="form-group form-check"><br/> <Field name="acceptTerms" type="checkbox" className="form-check-input"/> <label htmlFor="acceptTerms" className="form-check-label"> I have read and agree to the Terms </label> <ErrorMessage name="acceptTerms" component="div" className="text-danger"/> </div> <div className="form-group"> <button type="submit" className="btn btn-primary"> Register </button> <button type="button" onClick={resetForm} className="btn btn-warning"> Reset </button> </div> </Form> )} </Formik> </div> </div> ); } } export default App;http://localhost/devtest/reactjs/reg.php
//http://localhost/devtest/reactjs/reg.php <?php header("Access-Control-Allow-Origin: *"); //add this CORS header to enable any domain to send HTTP requests to these endpoints: $host = "localhost"; $user = "root"; $password = ""; $dbname = "testingdb"; $con = mysqli_connect($host, $user, $password,$dbname); $method = $_SERVER['REQUEST_METHOD']; if (!$con) { die("Connection failed: " . mysqli_connect_error()); } switch ($method) { case 'POST': $fullname = $_POST["fullname"]; $username = $_POST["username"]; $email = $_POST["email"]; $password = $_POST["password"]; $sql = "insert into tbl_user (fullname, username, email, password) values ('$fullname', '$username', '$email', '$password')"; break; } // run SQL statement $result = mysqli_query($con,$sql); // die if SQL statement failed if (!$result) { http_response_code(404); die(mysqli_error($con)); } if ($method == 'POST') { echo json_encode($result); } else { echo mysqli_affected_rows($con); } $con->close();