javascript - Moment.js: Check if string is in correct format -


i checking if moment string correct using regex specific format string:

const iscorrect = iscorrectformat('12/06/2016 20:20:20:444') 

and 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 result in case false because not using same format.

the problem want solve now, send format parameter, instead of using regex, want use directly moment format speficifation.

const iscorrect = iscorrectformat(     '12/06/2016 20:20:20:444',     'mm/dd/yyyy hh:mm:ss.sss' ) 

but don't have idea how implement it... found in documentation of moment , don't see method test it. idea?

thank much!!

you can use moment strict parsing , isvalid method.

as stated in moment(string, string) docs:

moment's parser forgiving, , can lead undesired/unexpected behavior.

as of version 2.3.0, may specify boolean last argument make moment use strict parsing. strict parsing requires format , 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>


Comments

Popular posts from this blog

python - Selenium remoteWebDriver (& SauceLabs) Firefox moseMoveTo action exception -

html - How to custom Bootstrap grid height? -

transpose - Maple isnt executing function but prints function term -