This is a React form validation step by step tutorial. In this tutorial, we will learn to build a basic form from scratch in React.
We will create a basic React app, in which we will create a basic user registration form using Bootstrap 4. This React form will allow us to register a user. It will have the following form fields such as name, email, and password.
Let’s start installing the basic React app for creating Form validation in React.
We will install the React app using create-react-app.
npx create-react-app react-form-validation
Get inside the project directory.
cd react-form-validation
Install Bootstrap 4 UI framework, and it offers many UI components. We will create user form using Bootstrap 4 in React.
npm install bootstrap --save
Next, import bootstrap.min.css from node_modules in src/App.js file.
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';
function App() {
return (
<div className="App">
<h3>React Form Validation Tutorial</h3>
</div>
);
}
export default App;
Create a component in React, create component folder inside the src folder then create user-form.component.js file. Next, paste the following code in here.
import React, { Component } from "react";
export default class UserForm extends Component {
render() {
return (
<div>
<h3>React Form Component</h3>
</div>
);
}
}
Next, import the UserForm component in src/App.js file.
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';
import UserForm from './component/user-form.component';
function App() {
return (
<div className="container">
<UserForm />
</div>
);
}
export default App;
Next, create a basic user form in React with the help of Bootstrap 4. We will add name, email, and password form elements inside the React’s UserForm component.
Add the code component/user-form.component.js file.
import React, { Component } from "react";
export default class UserForm extends Component {
render() {
return (
<form>
<div className="form-group">
<label>Name</label>
<input type="text" className="form-control" />
<small className="text-danger">Name is required.</small>
</div>
<div className="form-group">
<label>Email</label>
<input type="email" className="form-control" />
</div>
<div className="form-group">
<label>Password</label>
<input type="text" className="form-control" />
</div>
<button type="submit" className="btn btn-block btn-danger">Create User</button>
</form>
);
}
}
Forms are an essential part of any modern web and mobile applications, and forms allow software and human interaction in a straightforward way. In this step, we will validate a basic form and handle the form data in React.
Add the following code in src/component/user-form.component.js file.
To validate the email field, declare the regExp instance outside the React component using the RegExp object and pass the regular expression in the RegExp object.
const regExp = RegExp(
/^[a-zA-Z0-9][email protected][a-zA-Z0-9]+\.[A-Za-z]+$/
)
Next, we are using the formValid object, and this object is checking whether the form state is valid or not based on the isError object.
const formValid = ({ isError, ...rest }) => {
let isValid = false;
Object.values(isError).forEach(val => {
if (val.length > 0) {
isValid = false
} else {
isValid = true
}
});
Object.values(rest).forEach(val => {
if (val === null) {
isValid = false
} else {
isValid = true
}
});
return isValid;
};
We defined the name, email, password in React state along with isError object. This isError object will hold the form errors for every state.
export default class UserForm extends Component {
constructor(props) {
super(props)
this.state = {
name: '',
email: '',
password: '',
isError: {
name: '',
email: '',
password: ''
}
}
}
onSubmit = e => {
e.preventDefault();
if (formValid(this.state)) {
console.log(this.state)
} else {
console.log("Form is invalid!");
}
};
formValChange = e => {
e.preventDefault();
const { name, value } = e.target;
let isError = { ...this.state.isError };
switch (name) {
case "name":
isError.name =
value.length < 4 ? "Atleast 4 characaters required" : "";
break;
case "email":
isError.email = regExp.test(value)
? ""
: "Email address is invalid";
break;
case "password":
isError.password =
value.length < 6 ? "Atleast 6 characaters required" : "";
break;
default:
break;
}
this.setState({
isError,
[name]: value
})
};
render() {
const { isError } = this.state;
return (
<form onSubmit={this.onSubmit} noValidate>
<div className="form-group">
<label>Name</label>
<input
type="text"
className={isError.name.length > 0 ? "is-invalid form-control" : "form-control"}
name="name"
onChange={this.formValChange}
/>
{isError.name.length > 0 && (
<span className="invalid-feedback">{isError.name}</span>
)}
</div>
<div className="form-group">
<label>Email</label>
<input
type="email"
className={isError.email.length > 0 ? "is-invalid form-control" : "form-control"}
name="email"
onChange={this.formValChange}
/>
{isError.email.length > 0 && (
<span className="invalid-feedback">{isError.email}</span>
)}
</div>
<div className="form-group">
<label>Password</label>
<input
type="password"
className={isError.password.length > 0 ? "is-invalid form-control" : "form-control"}
name="password"
onChange={this.formValChange}
/>
{isError.password.length > 0 && (
<span className="invalid-feedback">{isError.password}</span>
)}
</div>
<button type="submit" className="btn btn-block btn-danger">Create User</button>
</form>
);
}
}
i hope you like this article.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Laravel 5.5 - Task Scheduling With Cron Job Example
Today, we are share in this tutorials &q...How to Read Any Request Header in PHP
You have already know that generally you...Laravel V5.4.28 is now released
The laravel team released laravel versio...How to disabled Submit Button after Clicked using jQuery
Often times, users like to press a few t...How to replace a word inside a string in PHP
Use the PHP str_replace() func...