React JS is a popular JavaScript library used for building user interfaces. It is used to create interactive and dynamic web applications. In this tutorial, we will learn how to create a simple registration form validation using React JS.
We will start by creating a basic HTML form with a few input fields. We will then add some basic validation rules to the form using React JS. Finally, we will add a submit button to the form and handle the form submission using React JS.
First, let’s create the HTML form. We will create a simple form with three input fields: name, email, and password. We will also add a submit button to the form.
Next, we will add some basic validation rules to the form using React JS. We will use the React Hooks API to add the validation rules. We will add a validation rule to check if the name field is not empty, if the email field is a valid email address, and if the password field is at least 8 characters long.
import React, { useState } from ‘react’;
const FormValidation = () => {
const [name, setName] = useState(”);
const [email, setEmail] = useState(”);
const [password, setPassword] = useState(”);
const [error, setError] = useState(”);
const handleSubmit = (e) => {
e.preventDefault();
if (name === ”) {
setError(‘Name is required’);
} else if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
setError(‘Email is invalid’);
} else if (password.length < 8) {
setError('Password must be at least 8 characters long');
} else {
setError('');
}
};
return (
);
};
export default FormValidation;
Finally, we will add a submit button to the form and handle the form submission using React JS. We will use the handleSubmit function to check if the form is valid and then submit the form data to the server.
import React, { useState } from ‘react’;
const FormValidation = () => {
const [name, setName] = useState(”);
const [email, setEmail] = useState(”);
const [password, setPassword] = useState(”);
const [error, setError] = useState(”);
const handleSubmit = (e) => {
e.preventDefault();
if (name === ”) {
setError(‘Name is required’);
} else if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
setError(‘Email is invalid’);
} else if (password.length < 8) {
setError('Password must be at least 8 characters long');
} else {
setError('');
// Submit the form data to the server
}
};
return (
);
};
export default FormValidation;
In this tutorial, we have learned how to create a simple registration form validation using React JS. We have used the React Hooks API to add the validation rules and handle the form submission.
[ad_1]
React registration/signup form validation; This tutorial will guide you from scratch on how to create registration form and add validation rules with form in react js apps.
This react js registration form validation tutorial will create form tag, 4 TextField components, and 1 Button components. The text fields will be for name, mobile/phone number, email, and password inputs. The 1 button will be used for signup. And the react registration/signup form will looks like:
Registration Form Validation in React js
Follow the following steps to implement validation on registration form in react js app:
- Step 1 – Create React App
- Step 2 – Install validator and Bootstrap
- Step 3 – Create Form Validation Class
- Step 4 – Create Registration Form in App.js
Step 1 – Create React App
In this step, open your terminal and execute the following command on your terminal to create a new react app:
npx create-react-app my-react-app
To run the React app, execute the following command on your terminal:
npm start
Check out your React app on this URL: localhost:3000
Step 2 – Install Validator and Bootstrap
In this step, execute the following command to install react boostrap library into your react app:
npm install bootstrap --save npm install --save validator
Add bootstrap.min.css file in src/App.js
file:
import React, { Component } from 'react'
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
function App() {
return (
<div>
<h2>How to Add Custom Validatin with Forms in React</h2>
</div>
);
}
export default App;
Step 3 – Create Form Validation Class
In this step, create FormValidator .js file. So, visit the src directory of your react js app and create a custom validation component file named FormValidator.js. And add the following code into it:
import validator from 'validator';
class FormValidator {
constructor(validations) {
this.validations = validations;
}
validate(state) {
let validation = this.valid();
// for each validation rule
this.validations.forEach(rule => {
if(!validation[rule.field].isInvalid) {
const field_value = state[rule.field].toString();
const args = rule.args || [];
const validation_method = typeof rule.method === 'string' ? validator[rule.method] : rule.method
if(validation_method(field_value, ...args, state) !== rule.validWhen) {
validation[rule.field] = {
isInvalid: true,
message: rule.message
}
validation.isValid = false;
}
}
});
return validation;
}
valid() {
const validation = {}
this.validations.map(rule => (validation[rule.field] = {
isInvalid: false,
message: ''
}));
return {
isValid: true,
...validation
};
}
}
export default FormValidator;
Note that, The validate() function check all field validation.
Step 4 – Create Registration Form in App.js
In this step, create a registration form and as well as well import FormValidator.js file in src/App.js
file:
import React, {Component} from 'react';
import FormValidator from './FormValidator';
import './App.css';
class App extends Component{
constructor(){
super();
this.validator = new FormValidator([{
field: 'full_name',
method: 'isEmpty',
validWhen: false,
message: 'Enter full name.'
}, {
field: 'email',
method: 'isEmpty',
validWhen: false,
message: 'Enter your email address.'
}, {
field: 'email',
method: 'isEmail',
validWhen: true,
message: 'Enter valid email address.'
}, {
field: 'phone',
method: 'isEmpty',
validWhen: false,
message: 'Enter a phone number.'
}, {
field: 'phone',
method: 'matches',
args: [/^\(?\d\d\d\)? ?\d\d\d-?\d\d\d\d$/],
validWhen: true,
message: 'Enter valid phone number.'
}, {
field: 'password',
method: 'isEmpty',
validWhen: false,
message: 'Enter password.'
}, {
field: 'password_confirmation',
method: 'isEmpty',
validWhen: false,
message: 'Enter Password confirmation.'
}, {
field: 'password_confirmation',
method: this.passwordMatch, // notice that we are passing a custom function here
validWhen: true,
message: 'Password and password confirmation do not match.'
}]);
this.state = {
full_name: '',
email: '',
phone: '',
password: '',
password_confirmation: '',
validation: this.validator.valid(),
}
this.submitted = false;
}
passwordMatch = (confirmation, state) => (state.password === confirmation)
handleInputChange = event => {
event.preventDefault();
this.setState({
[event.target.name]: event.target.value,
});
}
handleFormSubmit = event => {
event.preventDefault();
const validation = this.validator.validate(this.state);
this.setState({
validation
});
this.submitted = true;
if(validation.isValid) {
//reaches here if form validates successfully...
}
}
render() {
let validation = this.submitted ?this.validator.validate(this.state) : this.state.validation
return (
<div className="container">
<div className="row">
<div className="col-md-4 col-md-offset-4">
<form className="registrationForm">
<h2>Registration form validation react js - Tutsmake.com</h2>
<div className={validation.email.isInvalid && 'has-error'}>
<label htmlFor="full_name">Full Name</label>
<input type="string" className="form-control" name="full_name" placeholder="Full Name" onChange={this.handleInputChange} /> <span className="help-block">{validation.full_name.message}</span> </div>
<div className={validation.email.isInvalid && 'has-error'}>
<label htmlFor="email">Email address</label>
<input type="email" className="form-control" name="email" placeholder="Email address" onChange={this.handleInputChange} /> <span className="help-block">{validation.email.message}</span> </div>
<div className={validation.phone.isInvalid && 'has-error'}>
<label htmlFor="phone">Phone(enter only 10 digit number)</label>
<input type="phone" className="form-control" name="phone" placeholder="Phone Number" onChange={this.handleInputChange} /> <span className="help-block">{validation.phone.message}</span> </div>
<div className={validation.password.isInvalid && 'has-error'}>
<label htmlFor="password">Password</label>
<input type="password" className="form-control" placeholder="Password" name="password" onChange={this.handleInputChange} /> <span className="help-block">{validation.password.message}</span> </div>
<div className={validation.password_confirmation.isInvalid && 'has-error'}>
<label htmlFor="password_confirmation">Confirm Password</label>
<input type="password" className="form-control" placeholder="Confirm Password" name="password_confirmation" onChange={this.handleInputChange} /> <span className="help-block">{validation.password_confirmation.message}</span> </div>
<button onClick={this.handleFormSubmit} className="btn btn-primary"> Register </button>
</form>
</div>
</div>
</div>
)
}
}
export default App;
Conclusion
React registration/signup form validation example; In this tutorial, you have learned how to add validation rules on registration/signup forms field in react js apps.
Recommended React JS Posts
[ad_2]