ryan
ryan

Reputation: 91

Validate Date FORMAT (not date string) using MomentJS?

I've seen that you can use an ".isValid()" function to check that a given string is in a date format:

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

But is there a way to confirm that the format is correct? For example:

'YYYY-MM-DD' should return true, but

'YYYY-MM-DDsadsadl' should return false since the characters at the end of the string aren't valid DateTime chars.

We're working on a tool that allows a user to input an existing date format, and then a second input to enter the desired format, but we need validation to ensure the string can properly parse and convert, but they aren't entering a specific date.

The application must accept any and all possible date formats.

Upvotes: 4

Views: 1349

Answers (2)

Rajeev Ranjan
Rajeev Ranjan

Reputation: 4076

Use the following function to validate your format.

validFormat = function(inputFormat){
  var validation = moment(moment('2017-06-17').format(inputFormat), inputFormat).inspect(); 
  if(validation.indexOf('invalid') < 0) 
    return true; 
  else 
    return false;
}

Do spend some time to understand this. This simply does a reverse verification using inspect(). The date 2017-06-17 can be replaced by any valid date. This Moment Js Docs will help you identify the valid formats.

Just make a call to this function as

validFormat('YYYY MM DD')

Upvotes: 3

Slbox
Slbox

Reputation: 13118

const getIsValid = inputFormat => moment(moment().format(inputFormat), inputFormat).isValid()

Explanation:

moment().format(inputFormat) - Create a date string from the current time from that format

This is then wrapped with moment() to make that string a moment date object, defining the format to parse it with. Finally we call the isValid() property on that moment date object. This ensures we are able to both create and parse a moment with our custom format.

Upvotes: 2

Related Questions