Created
August 19, 2023 05:39
-
-
Save lakpahana/28ffe7f6515736c1c18a4c2353d1d973 to your computer and use it in GitHub Desktop.
CVV add slash and validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function formatString(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/' // 3 > 03/ | |
).replace( | |
/^(0[1-9]|1[0-2])$/g, '$1/' // 11 > 11/ | |
).replace( | |
/^([0-1])([3-9])$/g, '0$1/$2' // 13 > 01/3 | |
).replace( | |
/^(0?[1-9]|1[0-2])([0-9]{2})$/g, '$1/$2' // 141 > 01/41 | |
).replace( | |
/^([0]+)\/|[0]+$/g, '0' // 0/ > 0 and 00 > 0 | |
).replace( | |
/[^\d\/]|^[\/]*$/g, '' // To allow only digits and `/` | |
).replace( | |
/\/\//g, '/' // Prevent entering more than 1 `/` | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment