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
704 views
in Technique[技术] by (71.8m points)

validation - Using Javascript, how do I make sure a date range is valid?

In JavaScript, what is the best way to determine if a date provided falls within a valid range?

An example of this might be checking to see if the user input requestedDate is part of the next valid work week. Note that this is not just checking to see if one date is larger than another as a valid date would be equal to or greater than the lower end of the range while less than or equal to the upper end of the range.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is actually a problem that I have seen come up before a lot in my works and the following bit of code is my answer to the problem.

// checkDateRange - Checks to ensure that the values entered are dates and 
//     are of a valid range. By this, the dates must be no more than the 
//     built-in number of days appart.
function checkDateRange(start, end) {
   // Parse the entries
   var startDate = Date.parse(start);
   var endDate = Date.parse(end);
   // Make sure they are valid
    if (isNaN(startDate)) {
      alert("The start date provided is not valid, please enter a valid date.");
      return false;
   }
   if (isNaN(endDate)) {
       alert("The end date provided is not valid, please enter a valid date.");
       return false;
   }
   // Check the date range, 86400000 is the number of milliseconds in one day
   var difference = (endDate - startDate) / (86400000 * 7);
   if (difference < 0) {
       alert("The start date must come before the end date.");
       return false;
   }
   if (difference <= 1) {
       alert("The range must be at least seven days apart.");
       return false;
    }
   return true;
}

Now a couple things to note about this code, the Date.parse function should work for most input types, but has been known to have issues with some formats such as "YYYY MM DD" so you should test that before using it. However, I seem to recall that most browsers will interpret the date string given to Date.parse based upon the computers region settings.

Also, the multiplier for 86400000 should be whatever the range of days you are looking for is. So if you are looking for dates that are at least one week apart then it should be seven.


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

...