javascript - Auto-format credit card number input as user types -
i want create input using javascript automatically formats in correct credit card format.
what want?
- the input should format input in groups of 4. e.g. if typed in
1234567890123456
, should format1234 5678 9012 3456
- the max length should 16 digits. if typed in
1234567890123456789
should format "1234 5678 9012 3456" - formatting should occur type. if typed "123456" should format "1234 56"
- invalid characters should ignored. if typed in
564adsd299 474
should format "5642 9947 4"
the input should respect traditional behaviour of textbox. (the |
here resembles cursor e.g.
if typed in 8 when input is:
1234 5|67
should turn1234 58|67
1234|
, should turn1234 8
1234| 567
should turn1234 8567
1234| 5679
should turn1234 8567 9
if delete previous character when input is:
1234 5|67
should turn1234 |67
1234 |567
should turn1234| 567
1234| 567
should turn123|5 67
more test cases follow.
example
basically should behave "enter card details" used in google play store. find page: open play store on android device > click account > payment methods > add credit or debit card. screen can found here: https://play.google.com/store/account
what have far?
this have far:
var txtcardnumber = document.queryselector("#txtcardnumber"); txtcardnumber.addeventlistener("input", onchangetxtcardnumber); function onchangetxtcardnumber(e) { var cardnumber = txtcardnumber.value; // not allow users write invalid characters var formattedcardnumber = cardnumber.replace(/[^\d]/g, ""); formattedcardnumber = formattedcardnumber.substring(0, 16); // split card number groups of 4 var cardnumbersections = formattedcardnumber.match(/\d{1,4}/g); if (cardnumbersections !== null) { formattedcardnumber = cardnumbersections.join(' '); } console.log("'"+ cardnumber + "' '" + formattedcardnumber + "'"); // if formmattedcardnumber different shown, change value if (cardnumber !== formattedcardnumber) { txtcardnumber.value = formattedcardnumber; } }
<input id="txtcardnumber"/>
the above formats credit number perfectly, issues begin when want edit.
however, above not satisfy test cases 5 onward, cursor jumps end.
how can achieve behaviour. know it's possible google has done already.
(please no use paypal answers)
edit: note looking native javascript solutions, feel free suggest plugins comments. exception libraries little no dependencies it's possible copy source code.
i've removed jquery on above code encourage native js solutions.
i see you're using jquery, rather try solve logic consider using masked input plugin. chose this one because came first in search. there customization options , appears satisfy requirements.
$('#txtcardnumber').mask("9999 9999 9999 9999");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.js"></script> <input id="txtcardnumber"/>
Comments
Post a Comment