Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a string is valid date or not using moment?

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"

like image 630
Valamas Avatar asked Jan 30 '15 01:01

Valamas


People also ask

How do you check if a date is valid or not using moment?

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.

What is Moment () hour ()?

The moment(). hour() Method is used to get the hours from the current time or to set the hours. Syntax: moment().hour(); or. moment().

What is Moment () in JavaScript?

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.

How do you check if a date is a valid date in Java?

DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); assertTrue(validator. isValid("02/28/2019")); assertFalse(validator. isValid("02/30/2019"));


1 Answers

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 
like image 106
Luca Fagioli Avatar answered Oct 02 '22 03:10

Luca Fagioli