Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Validate Date

I have an HTML text field. I want to validate via JavaScript that the value entered is a valid date in the form of "MM/DD/YY" or "MM/D/YY" or "MM/DD/YYYY" or "MM/D/YYYY". Is there a function that does this?

I sort of assumed there was something like isNaN but I don't see anything. Is it true that JavaScript can't validate dates?

like image 740
user208662 Avatar asked Nov 19 '09 21:11

user208662


People also ask

What is date validation as text format in JavaScript?

This article is on Date Validation as Text Format in JavaScript. This will validate the Date being in the Text and validate with all the standard features. There are lots of validation libraries for Date Validation in JavaScript.

How to check if the date is valid in JavaScript?

Store the date object into a variable d. Check if the variable d is created by Date object or not by using Object.prototype.toString.call (d) method. If the date is valid then the getTime () method will always be equal to itself.

What are the different types of date validation?

Date validation. It is very important to validate the data supplied by the user through a form before you process it. Among various kind of data validation, validation of date is one. 1. dd/mm/yyyy or dd-mm-yyyy format.

What is the use of date method in JavaScript?

When a Date object is created, a number of methods allow you to operate on it. Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of date objects, using either local time or UTC (universal, or GMT) time.


2 Answers

You could use javascript's own Date object to check the date. Since the date object allows some mucking around with the month and day values (for example March 32 would be corrected to April 1), you can just check that the date you create matches the one you put in. You could shorten this if you want, but it's longer for clarity.

function checkDate(m,d,y)
{
   try { 

      // create the date object with the values sent in (month is zero based)
      var dt = new Date(y,m-1,d,0,0,0,0);

      // get the month, day, and year from the object we just created 
      var mon = dt.getMonth() + 1;
      var day = dt.getDate();
      var yr  = dt.getYear() + 1900;

      // if they match then the date is valid
      if ( mon == m && yr == y && day == d )
         return true; 
      else
         return false;
   }
   catch(e) {
      return false;
   }
}
like image 189
user1883048 Avatar answered Sep 24 '22 03:09

user1883048


Is it true that JavaScript can't validate dates?

No.

Is there a function that does this?

No.

You will need to write your own validation function to parse the date format (regex comes to mind) and then determine if it is valid within your specific criteria.

like image 28
Jani Hartikainen Avatar answered Sep 23 '22 03:09

Jani Hartikainen