简体   繁体   中英

How to validate credit card expiry date using Javascript or ReactJs?

in react I am using regex for month validation, initially I am allowing only two numbers using regex that is working fine for a month and year and able to validate months from 01 to 12, But stuck on how to validate expiry date for example now it is 06/22 I need to allow only numbers from 07/22.how to achieve that. below is my code:

for allowing only 2 nos: 
setInput({ ...input, [e.target.name]: e.target.value.replace(/\D/g, "").slice(0, 2) });

for allowing 1 to 12 nos below code is used onblur:

 let cardMonth = /^0[1-9]|1[0-2]/.test(e.target.value);
        if (cardMonth === true) {
          setInput({ ...input, [e.target.name]: e.target.value.replace(/\D/g, "").slice(0, 2) });
          setErrors({ ...errors, cardmonth: false });
        } else {
          setErrors({ ...errors, cardmonth: true });
        }

having two input fields for month and year.

Try this pattern, I used in my app and its was very helpfull :

function datePatten(e) {
    var code = e.keyCode;
    var allowedKeys = [8];
    if (allowedKeys.indexOf(code) !== -1) {
      return;
    }

    e.target.value = e.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 `/`
      );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM