Generate 4 Digit Random Pin and Validate in JavaScript

Generate 4 Digit Random Pin and Validate in JavaScript
Code Snippet:Pin Generator
Author: Toufiq-Gilani
Published: September 27, 2023
Last Updated: September 27, 2023
Downloads: 449
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code provides a simple user interface to generate and validate a 4-digit random PIN.

You can click the “Generate Pin” button to generate a random 4-digit PIN, and it will be displayed in the input field. Then, you can enter a PIN using the numeric buttons provided. The code also allows you to clear the entered PIN and provides feedback on whether the entered PIN matches the generated one.

This code is helpful for creating secure PIN generation and validation processes in web applications.

How to Generate 4 Digit Random Pin and Validate in JavaScript

1. First of all, load the Font Awesome icons kit by adding the following CDN link into the head tag of your web/app project.

<script src="https://kit.fontawesome.com/3b161c540c.js" crossorigin="anonymous"></script>

2. Create the HTML structure for your application. We’ll use a simple layout with two input fields, numeric buttons, and a message container.

<div class="container">
    <div class="card col">
      <input type="text" id="generatedPin" readonly>
      <button onclick="generatePin()" class="generate-pin-button">Generate Pin</button>
    </div>

    <div class="card slide">
      <input type="text" id="enteredPin" class="new-input" readonly>
      <div class="button-section">
        <div class="button-container">
          <button onclick="addNumber(1)" class="btn">1</button>
          <button onclick="addNumber(2)" class="btn">2</button>
          <button onclick="addNumber(3)" class="btn">3</button>
          <button onclick="addNumber(4)" class="btn">4</button>
          <button onclick="addNumber(5)" class="btn">5</button>
          <button onclick="addNumber(6)" class="btn">6</button>
          <button onclick="addNumber(7)" class="btn">7</button>
          <button onclick="addNumber(8)" class="btn">8</button>
          <button onclick="addNumber(9)" class="btn">9</button>
          <button onclick="backspace()" class="btn"><i class="fa-solid fa-arrow-left-long"></i></button>
          <button onclick="addNumber(0)" class="btn">0</button>
          <button onclick="clearInput()" class="btn">C</button>
        </div>
      </div>
      <button onclick="submitPin()" class="submit-btn">Submit</button>
      <p class="deadline"><span id="count-num"> 3 </span> try left</p>
    </div>
  </div>

  <div class="message-container" id="messageContainer">
    <span id="message"></span>
    <button onclick="closeMessage()" class="close-btn">
      <i class="fa-regular fa-rectangle-xmark"></i>
    </button>
  </div>

2. The following CSS code is responsible for styling our web application, including button styles, card animations, and layout adjustments for different screen sizes. You can customize the styles to match your design preferences.

* {
    box-sizing: border-box;
}

.container {
    display: flex;
    justify-content: center;
    gap: 1rem;
    padding-top: 0.5rem;
}

.card {
    background-color: rgb(34, 36, 54);
    padding: 0.7rem;
    width: 45%;
    max-width: 100%;
    border-radius: 0.5rem;
}

.col {
    display: flex;
    flex-direction: column;
    animation: slide-in-right 0.5s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
}

.slide {
    animation: slide-in-left 0.5s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
}

@keyframes slide-in-right {
    0% {
        -webkit-transform: translateX(1000px);
        transform: translateX(1000px);
        opacity: 0;
    }

    100% {
        -webkit-transform: translateX(0);
        transform: translateX(0);
        opacity: 1;
    }
}

@keyframes slide-in-left {
    0% {
        -webkit-transform: translateX(-1000px);
        transform: translateX(-1000px);
        opacity: 0;
    }

    100% {
        -webkit-transform: translateX(0);
        transform: translateX(0);
        opacity: 1;
    }
}

input[type="text"] {
    width: 75%;
    margin: 2rem auto;
    font-size: 1.2rem;
    padding: 0.75rem;
    color: rgb(255, 255, 255);
    outline: 0;
    border: 2px solid rgb(133, 130, 153);
    border-radius: 0.3rem;
    background-color: rgb(61, 65, 83);
}

.new-input {
    display: block;
    margin-left: auto;
    margin-right: auto;
}

.generate-pin-button {
    display: inline-block;
    width: 150px;
    height: 150px;
    border-radius: 50%;
    background-color: rgb(73, 91, 195);
    border: 10px solid rgb(57, 69, 140);
    color: rgb(255, 255, 255);
    margin: 5rem auto;
    text-align: center;
    font-size: 1rem;
    font-weight: 700;
    cursor: pointer;
}

.generate-pin-button:hover {
    opacity: 0.8;
}

.button-section {
    display: flex;
    justify-content: center;
}

.button-container {
    display: grid;
    grid-template-columns: repeat(3, 90px);
    gap: 0.5rem;
    text-align: center;
    margin: 0 auto;
}

.btn {
    cursor: pointer;
    background: rgb(66, 80, 98);
    color: rgb(255, 255, 255);
    width: 90px;
    padding: 1rem 0.5rem;
    border: 0;
    display: inline-block;
    font-size: 1.1rem;
    text-align: center;
    border-radius: 0.5rem;
}

.btn:is(:hover, :focus) {
    color: rgb(66, 80, 98);
    background: rgb(255, 255, 255);
}

.submit-btn {
    cursor: pointer;
    width: 60%;
    display: block;
    text-align: center;
    font-size: 1rem;
    letter-spacing: 0.1rem;
    padding: 0.75rem 1.5rem;
    border: 0;
    border-radius: 0.5rem;
    margin-top: 2rem;
    margin-left: auto;
    margin-right: auto;
    margin-bottom: 1rem;
    color: rgb(255, 255, 255);
    background-color: rgb(73, 91, 195);
}

.submit-btn:is(:hover, :focus) {
    color: rgb(73, 91, 195);
    background-color: rgb(255, 255, 255);
}

.deadline {
    margin: 0;
    text-align: center;
    margin-bottom: 1rem;
    color: rgb(220, 20, 60);
    letter-spacing: 0.1rem;
}

.message-container {
    width: 30%;
    text-align: center;
    margin: 1rem auto;
    background-color: rgb(255, 255, 255);
    padding: 0.8rem 1.2rem;
    border-radius: 0.3rem;
    display: none;
}

#message {
    font-size: 1rem;
    color: rgb(25, 25, 112);
}

.close-btn {
    cursor: pointer;
    background-color: transparent;
    border: 0;
    margin-left: 0.5rem;
}

.close-btn i {
    font-size: 1.3rem;
    color: rgb(220, 20, 60)
}

@media (max-width: 750px) {
    .container {
        flex-direction: column;
        align-items: center;
    }

    .card {
        padding: 0.7rem;
        width: 75%;
    }

    .button-container {
        grid-template-columns: repeat(3, 70px);
    }

    .btn {
        width: 70px;
    }

    .message-container {
        width: 75%;
    }
}

4. Finally, add the following JavaScript code to your project. It contains the logic for generating, entering, and validating the PIN. It also handles displaying messages to the user.

let generatedPin = "";
let enteredPin = "";

function generatePin() {
    generatedPin = Math.floor(1000 + Math.random() * 9000).toString();
    document.getElementById('generatedPin').value = generatedPin;
}

function addNumber(num) {
    enteredPin += num;
    document.getElementById('enteredPin').value = enteredPin;
}

function backspace() {
    enteredPin = enteredPin.slice(0, -1);
    document.getElementById('enteredPin').value = enteredPin;
}

function clearInput() {
    enteredPin = "";
    document.getElementById('enteredPin').value = enteredPin;
}

function submitPin() {
    const messageContainer = document.getElementById('messageContainer');
    const message = document.getElementById('message');

    if (enteredPin === generatedPin) {
        message.textContent = '✅ Pin matched!';
    } else {
        message.textContent = '❌ Pin not matched!';
    }

    messageContainer.style.display = 'block';

    // Try Count
    var countElement = document.getElementById("count-num");
    var count = parseInt(countElement.innerText);

    if (count > 1) {
        count--;
        countElement.innerText = " " + count + " ";
    } else {
        countElement.innerText = "❎ No try left";
        document.querySelector('.submit-btn').disabled = true;
    }
}

function closeMessage() {
    const messageContainer = document.getElementById('messageContainer');
    messageContainer.style.display = 'none';
}

That’s it! You’ve created a simple PIN generator and validator using HTML, CSS, and JavaScript. You can use this code as a foundation for more complex PIN-related features in your web applications. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X