skip to Main Content

I have an input field where users need to enter their PAN card number. The PAN card number has a specific format of 5 letters followed by 4 numbers and then 1 letter. For example: AAAAA1111A.

I want to enforce this specific format in real-time, so that users are restricted from entering any other format. The restriction should be applied as they type, rather than checking the format on form submission.

Is there a way to achieve this using HTML or JavaScript? How can I allow users to enter only 5 letters, then 4 numbers, and finally 1 letter, while preventing them from typing any other characters or breaking the format?

Any suggestions, code examples, or libraries that can help me implement this behavior would be greatly appreciated. Thank you!

4

Answers


  1. Try this code.

    $(document).ready(function(){     
      
      $(".pan").on('input',function(){
      var inputvalues = $(this).val();      
        var regex = /[A-Z]{5}[0-9]{4}[A-Z]{1}$/;    
        if(!regex.test(inputvalues))
        {      
          //$(".pan").val("");    
          alert("invalid PAN no");    
          return regex.test(inputvalues);    
        }    
      });          
    });    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    PAN : <input type="text" class="pan">    
    Login or Signup to reply.
  2. So you have 2 options when trying to do this, input fields have the pattern attribute that allows you to check if the input matches the provided pattern.

    <input type="text" id="inputBox" pattern="[A-Za-z]{5}[0-9]{4}[A-Za-z]"></input>
    

    However the only issue with that approach is it only validates the input on submit.

    The other option is to do it in javascript which would only allow the user to input characters if it matches the pattern.
    Something like the below Javascript would work

    const inputBox = document.getElementById("inputBox")
    
    inputBox.addEventListener("keydown", (event) => {
        event.preventDefault();
      
        if (event.key == 'Backspace') {
            inputBox.value = inputBox.value.substring(0, inputBox.value.length - 1)
        }
        
        if (event.key.length == 1) {
            const currentLength = inputBox.value.length
            const alphaValid = currentLength < 5 || currentLength == 9
            const numericValid = currentLength >= 5 && currentLength < 9
        
            if (alphaValid && event.key >= 'a' && event.key <= 'z' && event.ctrlKey == false) {
                inputBox.value += event.key.toUpperCase()
            } else if (alphaValid && event.key >= 'A' && event.key <= 'Z' && event.ctrlKey == false) {
                inputBox.value += event.key
            } else if (numericValid && event.key >= '0' && event.key <= '9' && event.ctrlKey == false) {
                inputBox.value += event.key
            }
        }
    })
    <input type="text" id="inputBox" pattern="[A-Za-z]{5}[0-9]{4}[A-Za-z]"></input>

    Code above isn’t perfect, there are no doubt edge cases that would break it, but it should give you a rough idea of what needs done.

    Login or Signup to reply.
  3. You can check the input value on input event and rollback the value to the previous value if it doesn’t match:

    const mask = 'AAAA1111A';
    const regex = {
      A: /[A-Z]/,
      1: /d/
    };
    let value = '';
    
    document.querySelector('input').addEventListener('input', ({target}) => {
    
      let idx = 0, valid = true;
      
      for(const c of target.value.split('')){
        if(target.value.length > mask.length || !regex[mask[idx++]].test(c)){
          valid = false;
          break;
        }
      }
      
      valid ? value = target.value : target.value = value;
    
    });
    <input>
    Login or Signup to reply.
  4. You can use plain vanilla Javascript and Regex for this.

    <html>
    <body>
    <label for="name">PAN Number</label>
    <input type="text" id="PanNum" name="panNum" onKeyUp="checkPanFormat()" required>    
    </body>
    
    <script>
        function checkPanFormat()
        {
            const panNum = document.getElementById("PanNum");
            const panNumVal = panNum.value;
            const panPattern = new RegExp(/^[a-zA-Z]{5}[0-9]{4}[a-zA-Z]{1}$/);
            if(panPattern.test(panNumVal)){
              panNum.style.color = 'green';
            }else {
              panNum.style.color = 'red';
            }
        }
    </script>    
    
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search