Regular expression date format to match date separator

I use the code below to check the date format in dd/mm/yyyyand format dd.mm.yyyy.

function validateDate(date){
    var matches, d, m, y, cDate, format, dateFormatObj;
    dateFormatObj = { format: /^(\d{2})[./](\d{2})[./](\d{4})$/, monthPos: 2, datePos:1,    yearPos:3}

    format = dateFormatObj.format;
    matches = format.exec(date);

    d = matches[dateFormatObj.datePos];
    m = matches[dateFormatObj.monthPos] - 1;
    y = matches[dateFormatObj.yearPos];
    cDate = new Date(y, m, d);

    return cDate.getDate() == d && cDate.getMonth() == m && cDate.getFullYear() == y;
}

alert(validateDate('22/05/2017'))

This works great for me to check the base date.

What I was trying to fix is ​​that if the separator (/ or.) Between the months, dates and years is different, then this should be invalidated.

I tried changing the regex format as /^(\d{2})[./](\d{2})\1(\d{4})$/, basically use the same captured group as indicated, but this does not seem to work, "match" is null. I read a couple of posts, but something seems to be missing. What can I do to make this work.

JS Fiddle - https://jsfiddle.net/90dstrx5/

0
2

:

/^(\d{2})([./])(\d{2})\2(\d{4})$/
//       ^            ^
//       |            +---- match capturing group #2
//       +----------------- capturing group #2

, "" 1-, 3- 4- ; 2- . , Array.splice(), :

function validateDate(date) {
  var matches, d, m, y, cDate, format, dateFormatObj;
  dateFormatObj = {
    format: /^(\d{2})([./])(\d{2})\2(\d{4})$/,
    monthPos: 2,
    datePos: 1,
    yearPos: 3
  };
  format = dateFormatObj.format;
  matches = format.exec(date);
  if (matches === null) {
    return false;
  }
  matches.splice(2, 1);
  d = matches[dateFormatObj.datePos];
  m = matches[dateFormatObj.monthPos] - 1;
  y = matches[dateFormatObj.yearPos];
  cDate = new Date(y, m, d);
  return cDate.getDate() == d && cDate.getMonth() == m && cDate.getFullYear() == y;
}
console.log(validateDate('22/05/2017')); // true
console.log(validateDate('22/05.2017')); // false
+3

, . .

function validateDate(date) {
  var matches, d, m, y, cDate, format, dateFormatObj;
  dateFormatObj = {
    format1: /^(\d{2})[.](\d{2})[.](\d{4})$/,
    format2: /^(\d{2})[/](\d{2})[/](\d{4})$/,
    monthPos: 2,
    datePos: 1,
    yearPos: 3
  }
  format1 = dateFormatObj.format1;
  format2 = dateFormatObj.format2;
  matches = format1.exec(date) || format2.exec(date);

  if (matches == null)
    return false;

  d = matches[dateFormatObj.datePos];
  m = matches[dateFormatObj.monthPos] - 1;
  y = matches[dateFormatObj.yearPos];
  cDate = new Date(y, m, d);
  return cDate.getDate() == d && cDate.getMonth() == m && cDate.getFullYear() == y;
}

alert(validateDate('22/05.2017'))
+1

Source: https://habr.com/ru/post/1691669/


All Articles