0

I am having trouble getting valid date formats using moment.js. I am not able to reject the entries which have only date and not time.

The date should be a "month-day-year" formatted (US style) and should include time in hours:min.

Examples of allowed formats:

  • 2/02/2019 0:00
  • 31/12/2019 0:00
  • 31/2/2019 00:00

Here is my code:

moment(item["InputDate"], 'MM/DD/YYYY HH:mm', true).isValid()

If I try to use strict formatting option, I am not able to validate the dates where there is a single digit date or month. I am taking this input from string type through excel input.

Is there a way to just check if the date is in the format mentioned and not having time?

Edit 1: I ended up listing out the valid formats and added them to strict validation using moment.js validation as a temporary workaround. But I am not sure if this is an exhaustive list of formats. I am using the below as the list of valid formats:

  1. "MM/DD/YYYY HH:mm"
  2. "MM/D/YYYY HH:mm"
  3. "M/DD/YYYY HH:mm"
  4. "MM/DD/YY HH:mm"
  5. "MM/DD/YYYY H:mm"
  6. "M/D/YYYY HH:mm"
  7. "M/DD/YY HH:mm"
  8. "M/DD/YYYY H:mm"
  9. "M/D/YY HH:mm"
  10. "M/D/YY H:mm"
  11. "MM/D/YY HH:mm"
Ashwini Maddala
  • 197
  • 1
  • 6
  • 26
  • 2
    Which input should be allowed? month-day-year + time or `31/12/2019 0:00` (that is day-month-year)? Anyway have a look at [`moment(String, String[], Boolean)`](http://momentjs.com/docs/#/parsing/string-formats/). – VincenzoC Jun 15 '18 at 09:36
  • Thanks. I need to allow dates in the format of MM/DD/YYYY HH:mm, MM/DD/YY HH:mm, m/d/YY H:mm. Any date without time should be rejected. – Ashwini Maddala Jun 15 '18 at 09:41

1 Answers1

0

If you're expecting a range of different formats, I'd suggest using a regular expression to validate the format, then loose value validation by moment.js. That way you don't have to think of every possible combination of strict format, e.g.

[
 '2/3/18 23:15',
 '2/3/18',
 '2/3/18 2:15',
 '2/3/2018 23:15',
 '12/13/2018 25:15', // invalid time
 '2/29/18 23:15',    // invalid date
 '12/03/2018 03:05'
].forEach(s => {
    var re = /\d\d?\/\d\d?\/\d{2,4}/;
    console.log(s + ' : ' + (re.test(s) && moment(s, 'M/D/YY HH:mm').isValid()));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

There are other ways to validate a date. Two digit years should be strongly discouraged unless you have an agreed algorithm for converting to 4 digit years. In javascript, two digit years are parsed as 20th century (i.e. "xx" as "19xx"), but some systems use a frame such as values from 0 to 30 are in the current century, 31 to 99 in the previous.

RobG
  • 142,382
  • 31
  • 172
  • 209