Tanzeel
Tanzeel

Reputation: 5038

How to check date format validation with moment

My question is regarding the validation of the format in which dates are entered. I want true if and only if the date is entered exactly in this format, MM-DD-YYYY. But my code simply validates dates with / (i.e. with slash) also. This means 02-29/2020, 01/30-2020 and even mix format like 02/-29-/2020 is also true. Also days, months and years have to be in 2 digit and 4 digit format respectively. I took help from: moment to validate date and time with custom format. I've created a stackblitz also. Here's my code:

validate(sDate: string, eDate: string) {
  this.isValidDate = true;
  this.startInvalid = false;
  this.endInvalid = false;
  this.dateErrors = new Set<string>();
  const fromDate = moment(sDate, "MM-DD-YYYY");
  console.log(fromDate.isValid());
  const toDate = moment(eDate, "MM-DD-YYYY");
  const currentDate = moment();
  if (fromDate.isAfter(toDate)) {
      this.dateErrors.add('Errors.StartDateMoreThanEndDate');
      this.startInvalid = true;
      this.isValidDate = false;
  }
    console.log(this.dateErrors);
    return this.isValidDate;
}

Is this even possible with moment or I'll have to write some regular expression for the same. I'm sorry if My entire implementation is wrong as first time I'm using moment.

Upvotes: 0

Views: 2324

Answers (2)

German Cosano
German Cosano

Reputation: 107

You can use the following sentence

moment(someDate, 'MM-DD-YYYY', true).isValid()

It will return a Boolean

Upvotes: 1

Matt Kosarek
Matt Kosarek

Reputation: 167

I believe when you construct the moment, you'd write something like this instead:

const myDate = moment(strDate, "MM-DD-YYYY", true)

where the last variable sets strict parsing to true (See docs here: https://momentjs.com/docs/#/parsing/)

Upvotes: 1

Related Questions