igorescobar / jQuery-Mask-Plugin

A jQuery Plugin to make masks on form fields and HTML elements.
http://igorescobar.github.io/jQuery-Mask-Plugin/
Other
4.77k stars 1.42k forks source link

Credit card date expiration #738

Open benfiratkaya opened 4 years ago

benfiratkaya commented 4 years ago

Hello I have https://gist.github.com/igorescobar/6450250#gistcomment-2307273 this code but I need more complicated masking.

If I write more than 1 when I write the month value, I want to add a leading zero. For example: If I write 2 it will turn into 02. 2/23 => 02/23

benfiratkaya commented 4 years ago

I update my code: It's work fine for me. You can develop this code:

if (typeof $.fn.mask === "function") {
  $('[data-format="card-expiry-date"]')
    .mask("AB/CD", {
      translation: {
        A: { pattern: /[0-9]/ },
        B: { pattern: /[0-9]/ },
        C: { pattern: /[2-9]/ },
        D: { pattern: /[0-9]/ }
      },
      onKeyPress: function(a, b, c, d) {
        if (!a) return;
        let m = a.match(/(\d{1})/g);
        if (!m) return;
        if (parseInt(m[0]) === 0) {
          d.translation.B.pattern = /[1-9]/;
        } else if (parseInt(m[0]) === 1) {
          d.translation.B.pattern = /[0-2]/;
        } else if (parseInt(m[0]) > 1) {
          c.val("0" + m[0] + "/");
        } else {
          d.translation.B.pattern = /[0-9]/;
        }
        let temp_value = c.val();
        c.val("");
        c.unmask().mask("AB/CD", d);
        c.val(temp_value);
      }
    })
    .keyup();
}

For example: 2/23 => 02/23 Min value: 01/20 Max value: 12/99