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
Try this code.
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.
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
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.
You can check the input value on
input
event and rollback the value to the previous value if it doesn’t match:You can use plain vanilla Javascript and Regex for this.