I have the following. For some reason, moment.js isnt validating my dates as expected. When i pass letters, it fails like its supposed to, but when using digits only, it always passes.
I'm using the MMDDYYYY format. How do I validate MMDDYYYY using moment? Thanks
var dates = "08291975"; //passes as it should
var passed = moment(dates, 'MMDDYYYY', true).isValid();
console.log('should pass ' + passed); //actual output is 'should pass true'
dates = "082919751"; //one digit too many should fail but doesnt
passed = moment(dates, 'MMDDYYYY', true).isValid();
console.log('should not pass ' + passed); //actual output is 'should not pass true'
dates = "0829ssss"; //fails as expected
passed = moment(dates, 'MMDDYYYY', true).isValid();
console.log('should not pass ' + passed); //actual output is 'should not pass false'
dates = "0829197"; //one digit short should fail but doesnt
passed = moment(dates, 'MMDDYYYY', true).isValid();
console.log('should not pass ' + passed); //actual output is 'should not pass true'
<script src="https://rawgit.com/moment/moment/2.2.1/min/moment.min.js"></script>
You can check whether the Moment considers the date invalid using moment#isValid . You can check the metrics used by #isValid using moment#parsingFlags , which returns an object.
The toISOString() method returns a string formatted as YYYY-MM-DDTHH:mm:ss. sssZ . If the ISO representation of the Date object starts with the provided string, we can conclude that the date string is valid and formatted as YYYY-MM-DD .
Date Formatting Date format conversion with Moment is simple, as shown in the following example. moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format.
You can have the expected output using last vesion (2.24.0), instead of the old 2.2.1.
Here a live sample:
var dates = "08291975";
var passed = moment(dates, 'MMDDYYYY', true).isValid();
console.log('should pass ' + passed);
dates = "082919751"; //one extra digit
passed = moment(dates, 'MMDDYYYY', true).isValid();
console.log('should not pass ' + passed);
dates = "0829ssss";
passed = moment(dates, 'MMDDYYYY', true).isValid();
console.log('should not pass ' + passed);
dates = "0829197"; //one digit missing
passed = moment(dates, 'MMDDYYYY', true).isValid();
console.log('should not pass ' + passed);
<script src="https://rawgit.com/moment/moment/2.24.0/min/moment.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With