I would like to test if a date and or time entered is valid.
Can this be done with moment as date and time testing with javascript seems a nightmare. (have spent hours on this).
Test data looks like this.
Invalid
invalid = "" invalid = " " invalid = "x" invalid = "1/1" invalid = "30/2/2015" invalid = "2/30/2015"
Is Valid
isvalid = "1/12/2015" isvalid = "1/12/2015 1:00 PM";
Have tried various javascript methods with hours of trials failing.
I thought moment would have something for this. So tried the following, all of which does not work because I do no think moment works like this.
var valid = moment(input).isDate() var valid = moment().isDate(input)
My time format is "dd/mm/yyyy"
isValid() is the method available on moment which tells if the date is valid or not. MomentJS also provides many parsing flags which can be used to check for date validation.
The moment(). hour() Method is used to get the hours from the current time or to set the hours. Syntax: moment().hour(); or. moment().
Moment JS allows displaying of date as per localization and in human readable format. You can use MomentJS inside a browser using the script method. It is also available with Node. js and can be installed using npm.
DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); assertTrue(validator. isValid("02/28/2019")); assertFalse(validator. isValid("02/30/2019"));
Moment has a function called isValid
.
You want to use this function along with the target date format and the strict parsing parameter to true (otherwise your validation might not be consistent) to delegate to the library all the needed checks (like leap years):
var dateFormat = "DD/MM/YYYY"; moment("28/02/2011", dateFormat, true).isValid(); // return true moment("29/02/2011", dateFormat, true).isValid(); // return false: February 29th of 2011 does not exist, because 2011 is not a leap year
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