Moment.js: Check if string is in correct format

Viewed 10525

I was checking if the moment string is correct using a regex with a specific format string:

const isCorrect = isCorrectFormat('12/06/2016 20:20:20:444')

and the isCorrectFormat function:

const isCorrectFormat = (dateString) => {
    const regex = /[0-3][0-9][/][0-9]{2}[/][0-9]{4} [0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]*/
    return regex.test(dateString)
}

And of course the result in this case will be false because is not using the same format.

The problem that I want to solve now, is send the format also as parameter, but instead of using a regex, I want to use directly the moment format speficifation.

const isCorrect = isCorrectFormat(
    '12/06/2016 20:20:20:444',
    'MM/DD/YYYY HH:mm:ss.SSS'
)

But I don't have idea how to implement it... I found in the documentation of moment and I don't see any method to test it. Any idea?

Thank you so much!!

2 Answers
Related