Creating a Secure Login Page in React: User Authentication Example

Published on
Jigar Patel-
4 min read

Overview

ExpertLaravel.com Image

Creating a Secure Login Page in React: User Authentication Example

Introduction

Looking to implement username and password validation in a React app? This article guides you through the process step by step.

Let's started

1. Setting Up Your React App:

To get started, create a new React app using the following command:

npx create-react-app my-app

2. Creating the DemoForm Component:

Now, let's create the DemoForm component to handle username, email, password, and confirm password validation:

import React from 'react';

class DemoForm extends React.Component {
  constructor() {
    super();
    this.state = {
      input: {},
      errors: {},
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    let input = this.state.input;
    input[event.target.name] = event.target.value;

    this.setState({
      input,
    });
  }

  handleSubmit(event) {
    event.preventDefault();

    if (this.validate()) {
      console.log(this.state);

      let input = {};
      input['username'] = '';
      input['email'] = '';
      input['password'] = '';
      input['confirm_password'] = '';
      this.setState({ input: input });

      alert('Demo Form is submitted');
    }
  }

  validate() {
    let input = this.state.input;
    let errors = {};
    let isValid = true;

    if (!input['username']) {
      isValid = false;
      errors['username'] = 'Please enter your username.';
    }

    if (typeof input['username'] !== 'undefined') {
      const re = /^\S*$/;
      if (input['username'].length < 6 || !re.test(input['username'])) {
        isValid = false;
        errors['username'] = 'Please enter valid username.';
      }
    }

    if (!input['email']) {
      isValid = false;
      errors['email'] = 'Please enter your email Address.';
    }

    if (typeof input['email'] !== 'undefined') {
      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(input['email'])) {
        isValid = false;
        errors['email'] = 'Please enter valid email address.';
      }
    }

    if (!input['password']) {
      isValid = false;
      errors['password'] = 'Please enter your password.';
    }

    if (!input['confirm_password']) {
      isValid = false;
      errors['confirm_password'] = 'Please enter your confirm password.';
    }

    if (typeof input['password'] !== 'undefined') {
      if (input['password'].length < 6) {
        isValid = false;
        errors['password'] = 'Please add at least 6 charachter.';
      }
    }

    if (
      typeof input['password'] !== 'undefined' &&
      typeof input['confirm_password'] !== 'undefined'
    ) {
      if (input['password'] != input['confirm_password']) {
        isValid = false;
        errors['password'] = "Passwords don't match.";
      }
    }

    this.setState({
      errors: errors,
    });

    return isValid;
  }

  render() {
    return (
      <div>
        <h1>Creating a Secure Login Page in React User Authentication Example</h1>
        <form onSubmit={this.handleSubmit}>
          <div class="form-group">
            <label for="username">Username:</label>
            <input
              type="text"
              name="username"
              value={this.state.input.username}
              onChange={this.handleChange}
              class="form-control"
              placeholder="Enter username"
              id="username"
            />

            <div className="text-danger">{this.state.errors.username}</div>
          </div>

          <div class="form-group">
            <label for="email">Email Address:</label>
            <input
              type="text"
              name="email"
              value={this.state.input.email}
              onChange={this.handleChange}
              class="form-control"
              placeholder="Enter email"
              id="email"
            />

            <div className="text-danger">{this.state.errors.email}</div>
          </div>

          <div class="form-group">
            <label for="password">Password:</label>
            <input
              type="password"
              name="password"
              value={this.state.input.password}
              onChange={this.handleChange}
              class="form-control"
              placeholder="Enter password"
              id="password"
            />

            <div className="text-danger">{this.state.errors.password}</div>
          </div>

          <div class="form-group">
            <label for="password">Confirm Password:</label>
            <input
              type="password"
              name="confirm_password"
              value={this.state.input.confirm_password}
              onChange={this.handleChange}
              class="form-control"
              placeholder="Enter confirm password"
              id="confirm_password"
            />

            <div className="text-danger">{this.state.errors.confirm_password}</div>
          </div>

          <input type="submit" value="Submit" class="btn btn-success" />
        </form>
      </div>
    );
  }
}

export default DemoForm;

3. Importing the Component:

To use the DemoForm component, import it into your index.js file. If you want to style your form with Bootstrap, follow our Bootstrap installation tutorial:

import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css'; // If you want to use Bootstrap
import DemoForm from './DemoForm';

ReactDOM.render(
  <React.StrictMode>
    <div className="container">
      <DemoForm />
    </div>
  </React.StrictMode>,
  document.getElementById('root')
);

4. Running Your Application:

Now, run your React app by executing this command:

npm start

Finally, open your browser and go to:

http://localhost:3000

Output

Output-1 Output-2 Output-3 Output-4

Quick summary

Follow these steps to set up secure username and password validation in your React app. Customize this example to meet your specific requirements, and you'll have a solid foundation for user authentication in your project. If you need help, feel free to reach out.

Source Code

The complete source code for this tutorial is available on GitHub. You can find it Here.

About the Author

Jigar Patel is a React.js enthusiast and a software developer at JBCodeapp Company. Visit our JBCodeapp to learn more about our work in the React.js ecosystem.

We're Hiring

Are you passionate about React.js development? We're always on the lookout for talented developers to join our team. Check out our careers page for current job openings.

  • A Beginner's Guide to Testing React Components with Jest and React Testing Library

  • Navigating the Premier React Libraries and Frameworks of 2023: A Comprehensive Overview

  • Why React is the Best Choice for Web App Development

  • Your Simplified React JS Developer Roadmap for 202

  • Simplified Guide to useEffect in React

  • React Bootstrap Modal Popup Example

  • Building a Blog Post Editor with React and CKEditor

  • Mastering React Debugging: Tips and Techniques for Effective Debugging

  • React Password Validation Made Easy: A Step-by-Step Guide