Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
75 views
in Technique[技术] by (71.8m points)

javascript - 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"

question from:https://stackoverflow.com/questions/28227862/how-to-test-a-string-is-valid-date-or-not-using-moment

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...