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.