CodeSolution

Please wait...

ReactJs Redux login and signup form validation and call rest full api using Axios

ReactJs Redux login and signup form validation and call rest full api using Axios

@ReactJs  @ Redux  @ login  @ signup  @ form  @ validation  @ api  @ Axios  

Reactjs is a popular frontend view library from facebook for creating single page apps.In today’s we are going to create basic login and sign up forms using npx create-react-app module of reactjs.
 

  • Create a project run this command:
npm install -g create-react-app
  • Then move into the newly created directory:
cd <project name>
  • Install required libary :
npm install --save bootstrap react-dom react-redux react-router-dom reactstrap axios
  • Rename then App.js => App.jsx src/App.js
  • After create components folder in src/components
  • After that create componets folder then create header compontent src/components/header/Header.jsx and add code 

 

Header.jsx

import React, { Component } from 'react'

import { Collapse,

Navbar,

NavbarToggler,

Nav,

NavItem } from 'reactstrap';

import { Link } from 'react-router-dom';

import './Header.css'

export default class Header extends Component {

constructor(props) {

super(props);

this.toggle = this.toggle.bind(this);

this.state = {

isOpen: false
};
}
toggle() {
this.setState({
  isOpen: !this.state.isOpen
});
}
render() {
return (
<div className="mb-50">
<Navbar color="faded" light fixed='top' expand="md">
<Link href="/" to="/"><img width="100%" src="http://www.codesolution.co.in/assets/images/logoicon.png" alt="Codesolution"/></Link>
<NavbarToggler onClick={this.toggle} />
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="ml-auto" navbar>
<NavItem>
<Link to="/">Home</Link>
</NavItem>
<NavItem>
<Link href="/login" to="/login">Login/Signup</Link>
</NavItem>
</Nav>
</Collapse>
</Navbar>
</div>
)
}
}

header.css

nav.navbar, .navbar-default { background-color: #7263bc !important; border-bottom:5px solid #323f45; padding-top:10px; } .navbar-default { background-image: none; border: none; border-radius: 0; } .mb-50{ margin-bottom: 60px; } .navbar-default .navbar-nav > li > a { color: white; } .navbar-default .navbar-brand { color: white; } .navbar-default .navbar-toggle { border-color: white; } .navbar-default .navbar-toggle .icon-bar { background-color: white; } .navbar-default .navbar-toggle:focus, .navbar-default .navbar-toggle:hover { background-color: transparent; } .navbar-default .navbar-brand:focus, .navbar-default .navbar-brand:hover { color: white; background-color: transparent; } a, a:hover{ color: #FFF !important; text-decoration: none; padding: 10px; } .navbar-default .navbar-nav>li>a:focus, .navbar-default .navbar-nav>li>a:hover { color: white; background-color: transparent; }
  • After then create footer folder in components and create Footer.jsx and css like that

Footer.jsx

import React, { Component } from 'react'

import './Footer.css'

export default class Footer extends Component {

render() {

return (

<div>

<footer className="footer">

<div className="container background_color">

<p className="text-center">Copyright @2019 | Designed With by <a href="http://wapptechlogics.in/" target="blank">Wapptechlogics</a></p>

</div>

</footer>

</div>

)
}
}

Footer.css

/*footer*/

footer { width:100%; background-color:#263238; min-height:auto; padding:5px 0px 5px 0px ;}

footer p { font-size:13px; color:#CCC; padding-bottom:0px; margin-bottom:8px;}

.background_color{

background: #7263bc;

border-radius: 0;

}
  • After then create home folder then create Login.jsx and css like that

Login.jsx

import React, { Component } from 'react';

import {Redirect, Link, router } from 'react-router-dom';

import {Button, Form, FormGroup, Label, Input} from 'reactstrap';

import './Login.css';

import axios from 'axios';

export default class Login extends Component {

componentDidMount() {

window.scrollTo(0, 0)

}

constructor(props) {

super(props);

this.state={

email: '',

password:'',

errors: {}

}

this.handleChangeEmail = this.handleChangeEmail.bind(this);

this.handleChangePassword = this.handleChangePassword.bind(this);

this.submituserRegistrationForm = this.submituserRegistrationForm.bind(this);

}

handleChangeEmail(e) {

this.setState({email:e.target.value});

}

handleChangePassword(e) {

this.setState({password:e.target.value});

}

submituserRegistrationForm(e) {

e.preventDefault();

if (this.validateForm()) {

console.log(this.state);

var apiBaseUrl = "http://localhost:1288/api/";

var data={

"user_email":this.state.email,

"password":this.state.password

}

var headers = {

'Content-Type': 'application/json',

}

console.log(data);

axios.post(apiBaseUrl+'login', data, {headers: headers}).then(function (response) {

console.log(response);

if(response.data.success){

localStorage.setItem("u_code", encodeURIComponent(JSON.stringify(response.data.data)));

localStorage.setItem('is_done', true);

window.location.href = "/";

console.log("Login successfull");

}else{

alert(response.data.message);

}

}).catch(function (error) {

console.log(error);

});

}

}

validateForm() {

let errors = {};

let formIsValid = true;

if (!this.state.email) {

formIsValid = false;

errors["email"] = "*Please enter your email-ID.";

}

if (typeof this.state.email !== "undefined") {

//regular expression for email validation

var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);

if (!pattern.test(this.state.email)) {

formIsValid = false;

errors["email"] = "*Please enter valid email-ID.";

}

}

if (!this.state.password) {

formIsValid = false;

errors["password"] = "*Please enter your password.";

}

if (typeof this.state.password !== "undefined") {

if (!this.state.password.match(/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%&]).*$/)) {

formIsValid = false;

errors["password"] = "*Please enter secure and strong password.";

}

}

this.setState({

errors: errors

});

return formIsValid;

}

render() {

return (

<div>

<div className="container">

<div className="row">

<div className="col-md-4 login-sec">

<h2 className="text-center">Login Codesolution</h2>

<Form method="post" name="userRegistrationForm" onSubmit= {this.submituserRegistrationForm} >

<FormGroup>

<Label for="exampleEmail">Email</Label>

<Input type="email" name="email" id="exampleEmail" value={this.state.email} onChange={this.handleChangeEmail} placeholder="Email Id" />

<div className="errorMsg">{this.state.errors.email}</div>

</FormGroup>

<FormGroup>

<Label for="examplePassword">Password</Label>

<Input type="password" name="password" id="examplePassword" value={this.state.password} onChange={this.handleChangePassword} placeholder="Password" />

<div className="errorMsg">{this.state.errors.password}</div>

</FormGroup>

<FormGroup check>

<Label check>

<Input type="checkbox" />{' '}

Remember Me

</Label>

</FormGroup>

<div className="d-flex justify-content-center mt-3 login_container">

<Button type="submit" className="btn btn-login">Submit</Button>

</div>

<div className="mt-4">

<div className="d-flex justify-content-center links">

Don't have an account? <Link href="/signup" to="/signup" className="linka">Sign Up</Link>

</div>

<div className="d-flex justify-content-center links">

<a className="linka">Forgot your password?</a>

</div>

</div>

</Form>

</div>

<div className="col-md-8 banner-sec"></div>

</div>

</div>

</div>

)

}

}

Login.css

@import url("//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css");
.login-block{

background: #7261be; /* fallback for old browsers */

background: -webkit-linear-gradient(to bottom, #FFB88C, #7261be); /* Chrome 10-25, Safari 5.1-6 */

background: linear-gradient(to bottom, #FFB88C, #7261be); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */

float:left;

width:100%;

padding : 50px 0;

}

.banner-sec{background:url(https://static.pexels.com/photos/33972/pexels-photo.jpg) no-repeat left bottom; background-size:cover; min-height:500px; border-radius: 0 10px 10px 0; padding:0;}

.container{background:#fff; border-radius: 0px; box-shadow:15px 20px 0px rgba(0,0,0,0.1);}

.carousel-inner{border-radius:0 10px 10px 0;}

.carousel-caption{text-align:left; left:5%;}

.login-sec{padding: 50px 30px; position:relative;}

.login-sec .copy-text{position:absolute; width:80%; bottom:20px; font-size:13px; text-align:center;}

.login-sec .copy-text i{color:#9286c7;}

.login-sec .copy-text a{color:#7261be;}

.login-sec h2{margin-bottom: 20px;

font-weight: bold;

font-size: 20px;

color: #7261be;}

.login-sec h2:after{content:" "; width:200px; height:5px;background: #25cf53;

display: block;

margin-top: 8px; border-radius:3px; margin-left:auto;margin-right:auto}

.btn-login{background: #7261be; color:#fff; font-weight:600;width: 100%;}

.banner-text{width:70%; position:absolute; bottom:40px; padding-left:20px;}

.banner-text h2{color:#fff; font-weight:600;}

.banner-text h2:after{content:" "; width:100px; height:5px; background:#FFF; display:block; margin-top:20px; border-radius:3px;}

.banner-text p{color:#fff;}

.login_container {

padding: 0 2rem;

}

.linka{

color:#7261be !important;

padding:0px !important;

}

.linka:hover{

color:#7261be !important;

padding:0px !important;

}

.errorMsg {

color: #cc0000;

margin-bottom: 12px;

}

.sucessMsg {

color: #6B8E23;

margin-bottom: 10px;

}
  • Create signup components

Signup.jsx

import React, { Component } from 'react';

import { Link } from 'react-router-dom';

import { Button, Form, FormGroup, Label, Jumbotron, Input} from 'reactstrap';

import './Signup.css';

import axios from 'axios';

export default class Signup extends Component {

componentDidMount() {

window.scrollTo(0, 0)

}

constructor(props) {

super(props);

this.state={

email: '',

name:'',

mobile:'',

password:'',

errors: {}

}

this.handleChangeName = this.handleChangeName.bind(this);

this.handleChangeMobile = this.handleChangeMobile.bind(this);

this.handleChangeEmail = this.handleChangeEmail.bind(this);

this.handleChangePassword = this.handleChangePassword.bind(this);

this.submituserRegistrationForm = this.submituserRegistrationForm.bind(this);

}

handleChangeName(e) {

this.setState({name:e.target.value});

}

handleChangeEmail(e) {

this.setState({email:e.target.value});

}

handleChangeMobile(e) {

this.setState({mobile:e.target.value});

}

handleChangePassword(e) {

this.setState({password:e.target.value});

}

submituserRegistrationForm(e) {

e.preventDefault();

if (this.validateForm()) {

console.log(this.state);

var apiBaseUrl = "http://localhost:1288/api/";

var data={

"name":this.state.name,

"user_email":this.state.email,

"mobile_number":this.state.mobile,

"password":this.state.password

}

var headers = {

'Content-Type': 'application/json',

}

console.log(data);

axios.post(apiBaseUrl+'createUsers', data, {headers: headers}).then(function (response) {

console.log(response);

if(response.data.success){

localStorage.setItem("u_code", encodeURIComponent(JSON.stringify(response.data.data)));

localStorage.setItem('is_done', true);

window.location.href = "/";

console.log("Login successfull");

}else{

alert(response.data.message);

}

}).catch(function (error) {

console.log(error);

});

}

}

validateForm() {

let errors = {};

let formIsValid = true;

if (!this.state.name) {

formIsValid = false;

errors["username"] = "*Please enter your username.";

}

if (typeof this.state.name !== "undefined") {

if (!this.state.name.match(/^[a-zA-Z ]*$/)) {

formIsValid = false;

errors["username"] = "*Please enter alphabet characters only.";

}

}

if (!this.state.email) {

formIsValid = false;

errors["email"] = "*Please enter your email-ID.";

}

if (typeof this.state.email !== "undefined") {

//regular expression for email validation

var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);

if (!pattern.test(this.state.email)) {

formIsValid = false;

errors["email"] = "*Please enter valid email-ID.";

}

}

if(!this.state.mobile) {

formIsValid = false;

errors["mobileno"] = "*Please enter your mobile no.";

}

if (typeof this.state.mobile !== "undefined") {

if (!this.state.mobile.match(/^[0-9]{10}$/)) {

formIsValid = false;

errors["mobileno"] = "*Please enter valid mobile no.";

}

}

if (!this.state.password) {

formIsValid = false;

errors["password"] = "*Please enter your password.";

}

if (typeof this.state.password !== "undefined") {

if (!this.state.password.match(/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%&]).*$/)) {

formIsValid = false;

errors["password"] = "*Please enter secure and strong password.";

}

}

this.setState({

errors: errors

});

return formIsValid;

}

render() {

return (

<div>

<div className="container">

<div className="row">

<div className="col-md-4 login-sec">

<h2 className="text-center">Signup Codesolution</h2>

<Form method="post" name="userRegistrationForm" onSubmit= {this.submituserRegistrationForm}>

<FormGroup>

<Label for="exampleName">Name</Label>

<Input type="text" name="name" id="name" value={this.state.name} onChange={this.handleChangeName} placeholder="Enter a name" />

<div className="errorMsg">{this.state.errors.name}</div>

</FormGroup>

<FormGroup>

<Label for="exampleMobile">Mobile No.</Label>

<Input type="text" name="mobile" id="exampleMobile" value={this.state.mobile} onChange={this.handleChangeEmail} placeholder="Enter a Mobile No." />

<div className="errorMsg">{this.state.errors.mobileno}</div>

</FormGroup>

<FormGroup>

<Label for="exampleEmail">Email</Label>

<Input type="email" name="email" id="exampleEmail" value={this.state.email} onChange={this.handleChangeMobile} placeholder="Enter a email" />

<div className="errorMsg">{this.state.errors.emailid}</div>

</FormGroup>

<FormGroup>

<Label for="examplePassword">Password</Label>

<Input type="password" name="password" id="examplePassword" value={this.state.password} onChange={this.handleChangePassword} placeholder="Enter a password" />

<div className="errorMsg">{this.state.errors.password}</div>

</FormGroup>

<div className="d-flex justify-content-center mt-3 login_container">

<Button type="submit" className="btn btn-login">Submit</Button>

</div>

<div className="mt-4">

<div className="d-flex justify-content-center links">

<Link href="/login" to="/login" className="linka">Already Account Login </Link>

</div>

</div>

</Form>

</div>

<div className="col-md-8 banner-sec"></div>

</div>

</div>

</div>

)

}

}

Singup.css

@import url("//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css");

.login-block{

background: #7261be; /* fallback for old browsers */

background: -webkit-linear-gradient(to bottom, #FFB88C, #7261be); /* Chrome 10-25, Safari 5.1-6 */

background: linear-gradient(to bottom, #FFB88C, #7261be); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */

float:left;

width:100%;

padding : 50px 0;

}

.banner-sec{background:url(https://static.pexels.com/photos/33972/pexels-photo.jpg) no-repeat left bottom; background-size:cover; min-height:500px; border-radius: 0 10px 10px 0; padding:0;}

.container{background:#fff; border-radius: 0px;box-shadow:15px 20px 0px rgba(0,0,0,0.1);}

.carousel-inner{border-radius:0 10px 10px 0;}

.carousel-caption{text-align:left; left:5%;}

.login-sec{padding: 50px 30px; position:relative;}

.login-sec .copy-text{position:absolute; width:80%; bottom:20px; font-size:13px; text-align:center;}

.login-sec .copy-text i{color:#9286c7;}

.login-sec .copy-text a{color:#7261be;}

.login-sec h2{margin-bottom: 20px;

font-weight: bold;

font-size: 20px;

color: #7261be;}

.login-sec h2:after{content:" "; width:200px; height:5px;background: #25cf53;

display: block;

margin-top: 8px; border-radius:3px; margin-left:auto;margin-right:auto}

.btn-login{background: #7261be; color:#fff; font-weight:600;width: 100%;}

.banner-text{width:70%; position:absolute; bottom:40px; padding-left:20px;}

.banner-text h2{color:#fff; font-weight:600;}

.banner-text h2:after{content:" "; width:100px; height:5px; background:#FFF; display:block; margin-top:20px; border-radius:3px;}

.banner-text p{color:#fff;}

.login_container {

padding: 0 2rem;

}

.linka{

color:#7261be !important;

padding:0px !important;

}

.linka:hover{

color:#7261be !important;

padding:0px !important;

}

.errorMsg {

color: #cc0000;

margin-bottom: 12px;

}

.sucessMsg {

color: #6B8E23;

margin-bottom: 10px;

}
  • Open App.jsx and add this code
import React, { Component } from 'react';

import { BrowserRouter as Router, Route } from 'react-router-dom';

import Home from './components/home/Home';

import Login from './components/login/Login';

import Signup from './components/signup/Signup';

import Navbar from './components/header/Header';

import Footer from './components/footer/Footer';

class App extends React.Component {

render() {

return (

<Router>

<div>

<Navbar />

<Route exact path="/" component={Home} />

<Route path="/login" component={Login} />

<Route path="/signup" component={Signup} />

<Footer />

</div>

</Router>

);

}

}

export default App;

After that run project you can create restfull api  and then check login/Signup.

 

youtube link : https://www.youtube.com/watch?v=sJ9BTZJf0ss

Thankyou 

Comments 0

Reply