Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate MMDDYYYY format using Moment [duplicate]

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>
like image 968
BoundForGlory Avatar asked Jul 30 '19 15:07

BoundForGlory


People also ask

How do you check if a moment object is valid?

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.

How do you check if the date is in YYYY MM DD format in js?

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 .

How do I change a moment date to a specific format?

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.


1 Answers

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>
like image 130
VincenzoC Avatar answered Oct 17 '22 08:10

VincenzoC