I have an app, user can specify their own data format, like 'MM/dd/yyyy', 'MM/dd/yy', etc.
Once I receive a date string, I need to validate if the date string is valid for the given format.
I tried to use moment(dataString, dateFormat).isValid(), but looks it does not do the work
For dateString: 01/01/20
with dateFormat MM/dd/yyyy, expect false
with dataFormat MM/dd/yy, expect true
moment('01/01/2020', 'MM/dd/yy').isValid() --- expect: false, actual: true
moment('01/02/2020', 'MM/dd/yyyy', true).isValid() --- expect: true, actual: false
What I can use to achieve this?
you have to capitalize DD and supply true in the 3rd parameter, to enable strict parsing
console.log(moment('This string includes a date with slashes 01/01/2020', 'MM/DD/YYYY').isValid())
console.log(moment('This string does not include a date with slashes', 'MM/DD/YYYY').isValid())
console.log(moment('01/01/2020', 'MM/DD/YYYY', true).isValid())
console.log(moment('01/01/2020', 'MM/dd/YYYY', true).isValid())
console.log(moment('01/01/20', 'MM/dd/YYYY', true).isValid())
console.log(moment('01/01/20', 'MM/DD/YY', true).isValid())
<script src="https://momentjs.com/downloads/moment.min.js"></script>