简体   繁体   中英

Javascript credit card expiry date validation

I'm currently using javascript validation to validate that the user inputs a valid date, however, my current regex patterns do not validate that the user must not be able to input a date less than 03/19. Instead, it allows 01/19 and also 02/19 etc.

I believe there are other ways to do this verification in javascript however I was wondering if there was a way with this regex.

current javascript:

var errdiv = $(".error");
  $("#form").validate({
    rules: {
      cardmm: {
        required: true,
        minlength: 2,
        maxlength: 2,
        pattern: "^(1[0-2]|[0-9]|)$"
      },
      cardyy: {
        required: true,
        minlength: 2,
        maxlength: 2,
          pattern: "^(2[0-8]|19|)$"
      },
    },
    messages: {
      cardmm: {
        required: "Please enter valid details.",
        minlength: "Please enter valid details.",
        maxlength: "Please enter valid details.",
        max: "Please enter valid details.",
        pattern: "Please enter valid details."
      },
      cardyy: {
        required: "Please enter valid details.",
        minlength: "Please enter valid details.",
        maxlength: "Please enter valid details.",
        pattern: "Please enter valid details."
      },
    },
    errorPlacement: function(error, element, m) {
      errdiv.css({"display": "block"});
      errdiv.empty();
      errdiv.text(error[0].innerHTML);
    },
    success: function(error) {
        error.removeClass("error");  // <- no, no, no!!
        errdiv.css({"display": "none"});
    }
  });

您可以将问题分为两部分:年份大于2019的任意日期的正则表达式,以及要允许2019年的特定月份的正则表达式,然后将它们合并为最终的正则表达式。

You could always invoke a little script that combines the mm and yy fields of the form to validate as a whole.

Join the fields with a forward slash.

The validation regex is then:

^(?:(?:0?[3-9]|1[0-2])/19|(?:0?[1-9]|1[0-2])/2[0-8])$

Expanded

 ^ 
 (?:
      (?: 0? [3-9] | 1 [0-2] )
      /19
   |  
      (?: 0? [1-9] | 1 [0-2] )
      /2 [0-8] 
 )
 $ 

Otherwise, it really can't be validated separately.

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