I want to create an input using JavaScript that automatically formats it in the correct credit card format.
What I want?
- The input should format the input in groups of 4, for example. If I dialed
1234567890123456 , it should format it to 1234 5678 9012 3456 - The maximum length must be 16 digits. Therefore, if I dialed
1234567890123456789 , it should format it to "1234 5678 9012 3456" - formatting should occur as you type. Therefore, if I dialed "123456", it should format it to "1234 56"
- Incorrect characters should be ignored. Therefore, if I dialed
564adsd299 474 , he should format it to "5642 9947 4"
Input should also take into account the traditional behavior of the text field. ( | here resembles a cursor, for example.
If I typed 8 when input:
1234 5|67 he should go to 1234 58|671234| he must turn to 1234 81234| 567 1234| 567 he must go to 1234 85671234| 5679 1234| 5679 he must turn to 1234 8567 9
If I delete the previous character when input:
1234 5|67 he must turn to 1234 |671234 |567 he must go to 1234| 567 1234| 5671234| 567 1234| 567 he must turn to 123|5 67
Most likely, other test cases will follow.
Example
Basically, it should behave exactly like the βEnter card detailsβ used in the Google Play Store. To find this page: Open the Play Store on your Android device> Click on "Account"> "Payment methods"> "Add credit or debit card." This screen can also be found here: https://play.google.com/store/account
What do I have so far?
This is what I have so far:
var txtCardNumber = document.querySelector("#txtCardNumber"); txtCardNumber.addEventListener("input", onChangeTxtCardNumber); function onChangeTxtCardNumber(e) { var cardNumber = txtCardNumber.value;
<input id="txtCardNumber"/>
The above credit number format is excellent, but problems begin when I want to edit.
However, the above does not satisfy test cases 5, since the cursor simply skips to the end.
How can I achieve this behavior. I know this is possible since Google has already done this.
(Please do not use PayPal answers)
Edit: Please note that I am looking for my own JavaScript solutions, but feel free to suggest plugins as comments. Libraries with minor dependencies are an exception, so you can simply copy the source code.
I also uninstalled jQuery in the above code to encourage JS native solutions.
source share