Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Regex Credit Card expiry date auto format

I'm trying to write a function that will get content from input element and try to format numbers entered in input box in MM/YY. Following is a solution that I've, I want to reduce numbers of lines it has. Can anybody help me write a better function to do this?

If you see this, it auto inserts slash. Working demo: https://codepen.io/ermauliks/pen/EXBryQ?editors=1010

function formatString(string) {
        return string.replace(
            /^([1-9]\/|[2-9])$/g, '0$1/' // To handle 3/ > 03/
        ).replace(
            /^(0[1-9]{1}|1[0-2]{1})$/g, '$1/' // 11 > 11/
        ).replace(
            /^([0-1]{1})([3-9]{1})$/g, '0$1/$2' // 13 > 01/3
        ).replace(
            /^(\d)\/(\d\d)$/g, '0$1/$2' // To handle 1/11 > 01/11
        ).replace(
            /^(0?[1-9]{1}|1[0-2]{1})([0-9]{2})$/g, '$1/$2' // 141 > 01/41
        ).replace(
            /^([0]{1,})\/|[0]{1,}$/g, '0' // To handle 0/ > 0 and 00 > 0
        ).replace(
            /[^\d\/]|^[\/]{0,}$/g, '' // To allow only numbers and /
        ).replace(
            /\/\//g, '/' // Prevent entering more than 1 /
        );
    }
    event.target.value = formatString(value);
like image 799
Maulik Suchak Avatar asked Dec 05 '25 08:12

Maulik Suchak


1 Answers

Here is an enhancement version where user doesn't enter the / (automatically added) and allows deletion (other solutions block on deleting the slash):

function cc_expires_format(string) {
    return string.replace(
        /[^0-9]/g, '' // To allow only numbers
    ).replace(
        /^([2-9])$/g, '0$1' // To handle 3 > 03
    ).replace(
        /^(1{1})([3-9]{1})$/g, '0$1/$2' // 13 > 01/3
    ).replace(
        /^0{1,}/g, '0' // To handle 00 > 0
    ).replace(
        /^([0-1]{1}[0-9]{1})([0-9]{1,2}).*/g, '$1/$2' // To handle 113 > 11/3
    );
}
like image 146
Luis Avatar answered Dec 06 '25 22:12

Luis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!