Aral Roca
Aral Roca

Reputation: 5919

Moment.js: Check if string is in correct format

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!!

Upvotes: 7

Views: 12667

Answers (2)

tyler_mitchell
tyler_mitchell

Reputation: 1747

You can do this using moment:

var date = moment('12/06/2016 20:20:20:444', 'MM/DD/YYYY HH:mm:ss.SSS');  

And then use moments validation:

date.isValid(); // returns true or false

http://momentjs.com/docs/#/parsing/string-format/

Upvotes: 2

VincenzoC
VincenzoC

Reputation: 31482

You can use moment strict parsing and isValid method.

As stated in moment(String, String) docs:

Moment's parser is very forgiving, and this can lead to undesired/unexpected behavior.

As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly, including delimeters.

Herea working sample:

const isCorrectFormat = (dateString, format) => {
    return moment(dateString, format, true).isValid()
}

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

console.log(isCorrect);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Upvotes: 20

Related Questions