skip to Main Content

How can you format a form input field such that it only accepts numbers from users, takes a maximum of 16 digits, and adds a space after each four digits? I am trying to create a debit card such that the data a user enters in the form input fields are updated in real time on the card displayed by the side. And I want the card number to be arranged in fours, just as it is on a real card.

I tried saving the user input in a variable and then using a loop to insert a space after every four digits. Well, I don’t know why but it didn’t work.

2

Answers


  1. I made a simple example using listeners and regular expressions.

    const input = document.querySelector('input');
    const show = document.querySelector('.card-number');
    
    input.addEventListener('input', () => {
      const cardNumber = input.value.replace(/s/g, '');
      const formatted = cardNumber.match(/.{1,4}/g).join(' ');
      show.textContent = formatted;
    });
    .card-preview {
      width: 250px;
      border: 1px solid #ccc;
      padding: 10px;
      margin-top: 20px;
    }
    
    .card-number {
      font-size: 18px;
      font-weight: bold;
    }
    <input type="text" placeholder="Enter Card Number" maxlength="16">
      <div class="card-preview">
        <div class="card-number"></div>
        <!--<div class="card-number">XXXX XXXX XXXX XXXX</div>-->
      </div>
    Login or Signup to reply.
  2. You can add an event listener that uses regex that modifies the number input by the user:

    JavaScript

    document.addEventListener('DOMContentLoaded', function() {
      const creditCardInput = document.getElementById('userInput');
      const formattedNumber = document.getElementById('displayedNumber');
    
      creditCardInput.addEventListener('input', function(e) {
          let inputValue = e.target.value.replace(/D/g, '');      
          inputValue = inputValue.substring(0, 16);      
          let formattedValue = inputValue.replace(/(d{4})(?=d)/g, '$1 ');      
          e.target.value = formattedValue;
          formattedNumber.textContent = formattedValue;
      });
    });
    

    Minimal HTML page:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Example CC input formatter</title>
    </head>
    <body>
        <label for="userInput">User Input:</label>
        <input type="text" id="userInput" maxlength="19">
        <p>Displayed Number (with formatting): <span id="displayedNumber"></span></p>
    
        <script src="script.js"></script>
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search