The issue I am having is that if you type quickly, it doesn’t convert this correctly to MM/YY, something like the following could happen:
Secondly, pasting in the value I would expect to auto convert as well. I tried adding paste to no avail.
Here’s a JSFIDDLE.
$('.card-expiry').on('keyup change blur', function(e) {
formatCCExpiryDate(e);
});
function formatCCExpiryDate(e) {
var inputChar = String.fromCharCode(event.keyCode);
var code = event.keyCode;
var allowedKeys = [8];
if (allowedKeys.indexOf(code) !== -1) {
return;
}
event.target.value = event.target.value.replace(
/^([1-9]/|[2-9])$/g, '0$1/'
).replace(
/^(0[1-9]|1[0-2])$/g, '$1/'
).replace(
/^([0-1])([3-9])$/g, '0$1/$2'
).replace(
/^(0?[1-9]|1[0-2])([0-9]{2})$/g, '$1/$2'
).replace(
/^([0]+)/|[0]+$/g, '0'
).replace(
/[^d/]|^[/]*$/g, ''
).replace(
////g, '/'
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<label>Expiration</label>
<div class="inline-fields">
<input class="card-expiry" placeholder="MM / YY" type="tel" maxlength="5" x-autocompletetype="cc-exp" autocompletetype="cc-exp" autocorrect="off" spellcheck="off" autocapitalize="off">
</div>
2
Answers
You can try the
input
event instead of the keyup event. The input event will fire for each input change, including paste operations, ensuring the format is updated in real-time.You might want to use input or keydown event, instead of keyup event. Keyup will fail when you press a key, and then before releasing it, press another. This may cause a problem as on fast typing there may be multiple keys which may not be released. For example, if you continuously press 1 you will end up with 11111 rather then 11/11. To handle the pasting option you can use input event in jQuery see the following example.