Hien Nguyen
Hien Nguyen

Reputation: 18975

momentjs did not validate hour/minute/second

I have a input support select date time picker with second. I use momentjs for convert value from input to date time format.

When I input value in input like this:

22-09-2019 15:ppp15:33
22-09-2019 1xx5:15:33
22-09-2019 15:15:test33

Moment object still show isValid. Can you explain why isValid is true in this case? How can I do for validate hour/minute/second for this?

I used library ng-pick-datetime in angular 5. enter image description here enter image description here

Upvotes: 0

Views: 386

Answers (1)

VincenzoC
VincenzoC

Reputation: 31482

You have to use strict mode parsing:

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.

See also Strict Mode guide, here a live sample:

['22-09-2019 15:ppp15:33',
'22-09-2019 1xx5:15:33',
'22-09-2019 15:15:test33',
'22-09-2019 15:15:33'].forEach((item) => {
  console.log(item, moment(item, 'DD-MM-YYYY HH:mm:ss', true).isValid() );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Upvotes: 2

Related Questions