codet
codet

Reputation: 3

How do validate date by 2 digit year

I have a script to validate card number expiry date. it validates so past date is valid. How do i amend so it validates a 2 digit entry and not 4?

11/2020 < current 11/20 < required

    $.validator.addMethod("expirydate", function (value, element) {
    var year = value.split('/');
    var date_str = year[1] + '-' + year[0];
    var today = new Date();

    var expirydate = new Date(date_str);
    if (value.match(/^\d\d?\/\d\d\d\d$/) && (year[0] > today.getMonth()) && (year[1] >= today.getFullYear()))
        return true;
    else
        return false;
}, "You must input a valid expiry date");

Upvotes: 0

Views: 1193

Answers (2)

Twisty
Twisty

Reputation: 30893

Consider the following code.

$(function() {
  function padZero(n) {
    return n < 9 ? "0" + n : n;
  }
  $("button").click(function() {
    var value = $("input").val();
    var now = new Date();
    var a = value.split("/");
    var b = [
      now.getMonth() + 1
    ];
    var result = false;
    if (a[1].length == 2) {
      b[1] = parseInt(now.getFullYear().toString().slice(-2));
    } else {
      b[1] = now.getFullYear();
    }
    if (a[1] < b[2]) {
      console.log("Fail", a, b);
    } else {
      if (a[0] < b[0]) {
        console.log("Fail", a, b);
      } else {
        console.log("Pass", a, b);
      }
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Exp. Date <input type="text" /> <button>Test</button>

You can adapt this to fit your needs.

Upvotes: 0

Δ O
Δ O

Reputation: 3710

  1. check the field's value integrity
  2. make checkDate a Date object out of year and month strings
  3. shift checkDate 1 month
  4. compare checkDate with current date
$.validator.addMethod("expirydate", function (value, element) {
  // check the field's value integrity (MM/YY or MM/YYYY)
  if (!value.match(/^(\d{2})\/(\d{2,4})/)) return false;

  // get month and year from "11/20" or "11/2020"
  let [ month, year ] = value.split('/');

  // make "20" into "2020"
  if (year.length < 4) year = '20' + year;

  // set checkDate to 2020-11-01
  let checkDate = new Date(year + "-" + month);

  // add 1 month to checkDate to make it valid until the end of the month 
  checkDate.setMonth(checkDate.getMonth() + 1);

  // return bool whether modified checkDate is in future
  return (checkDate > new Date());
}, "You must input a valid expiry date");

Upvotes: 1

Related Questions