8

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?

Alberto De Caro
5,2139 gold badges51 silver badges77 bronze badges
asked Nov 19, 2009 at 21:03
1
  • 3
    Javascript can't validate dates. But you can validate dates with Javascript. Commented Nov 19, 2009 at 21:05

11 Answers 11

12

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;
 }
}
answered Oct 13, 2013 at 2:51
Sign up to request clarification or add additional context in comments.

Comments

7

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.

answered Nov 19, 2009 at 21:06

4 Comments

I like how this was downvoted even though I explicitly answered both of the questions and provided additional information :P
this answer is very precise and quite useless without the example
Agreed, only half an answer
It looks like a complete answer to me.
6

Check out http://momentjs.com/. Using it, this snippet

moment(yourCandidateString, 'MM-DD-YYYY').isValid()

should do the job.

answered Mar 18, 2013 at 11:37

Comments

3

This is what I use to validate a date.

Date.parse returns NaN for invalid dates.

This supports both date-only and date+time formats.

Hope this helps.

var msg;
var str = "2013-12-04 23:10:59";
str = "2012/12/42";
var resp = Date.parse(str);
if(!isNaN(resp)) { msg='valid date'; } else { msg='invalid date'; }
console.log(msg);
answered Mar 24, 2014 at 11:41

1 Comment

This is not a good approach. As mentioned in user1883048's answer, some of the javascript engines will parse invalid dates. 2/31/2014 becomes 3/3/2014. 55/55/5555 becomes some time in the year 2024 in Firefox.
2

There does not appear to be a build-in function which does that. However, this code is probably what you're looking for:

<script type="text/javascript">
/**--------------------------
//* Validate Date Field script- By JavaScriptKit.com
//* For this script and 100s more, visit http://www.javascriptkit.com
//* This notice must stay intact for usage
---------------------------**/
function checkdate(input){
 var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
 var returnval=false
 if (!validformat.test(input.value))
 alert("Invalid Date Format. Please correct and submit again.")
 else{ //Detailed check for valid date ranges
 var monthfield=input.value.split("/")[0]
 var dayfield=input.value.split("/")[1]
 var yearfield=input.value.split("/")[2]
 var dayobj = new Date(yearfield, monthfield-1, dayfield)
 if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
 alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
 else
 returnval=true
 }
 if (returnval==false) input.select()
 return returnval
}
</script>

Source: http://www.javascriptkit.com/script/script2/validatedate.shtml

answered Nov 29, 2013 at 3:26

Comments

1

If you want to venture into the realms of JQuery there are plenty of validation plugins that include date validation. This plugin is one I've used a few times and has served me well.

answered Nov 19, 2009 at 21:12

Comments

1

I use Bootstrap Datepicker. One of the options with the text box disabled should do the trick.

http://www.eyecon.ro/bootstrap-datepicker/

answered May 4, 2013 at 10:09

Comments

1
<input type="text" id="dateinput"/>
<script type="text/javascript">
 $(#"dateinput").datepicker({
 buttonImage: "images/calendar.png",
 dateFormat: "yyyy-MMM-dd"
 });
 function validateDate() {
 if ($(#"dateinput").val().trim() == "") {
 // Is a blank date allowed?
 return true;
 }
 var oldVal = $(#"dateinput").val(); // Current value in textbox
 // Now use jQueryUI datepicker to try and set the date with the current textbox value
 $(#"dateinput").datepicker("setDate",$(#"dateinput").val());
 // Check if the textbox value has changed
 if (oldVal != $(#"dateinput").val()) {
 // The datepicker will set something different if the date is invalid
 $(#"dateinput").val(oldVal); // Set the textbox back to the invalid date
 alert ("date was invalid");
 return false;
 } else {
 // If nothing changed, the date must be good.
 return true;
 }
 }
</script>
answered Oct 4, 2013 at 8:01

Comments

1

Similar to this answer, Date can be used to check if the parsed version of the string corresponds to the original date string.

> datestring_valid = "2020年02月29日";
> parsed_Date = new Date(datestring_valid);
> parsed_Date.toISOString().slice(0,10) == datestring_valid;
true
> datestring_invalid = "2021-02-29";
> parsed_Date = new Date(datestring_invalid);
> parsed_Date.toISOString().slice(0,10) == datestring_invalid;
false

NB: This requires the date string to be ISO formatted.

The reason this works is, that Date parses some invalid dates into something valid as in the example above. However, supplying "2020-01-32" into Date will result in the result being "Invalid Date" that isNaN.

A function that handles all of this is the following:

function isValidDateString(datestring) {
 parsed_Date = new Date(datestring);
 return (parsed_Date.toISOString().slice(0,10) == datestring) && !isNaN(parsed_Date)
};
> isValidDateString(datestring_valid)
true
> isValidDateString(datestring_invalid)
false
answered May 31, 2021 at 18:22

Comments

0

Have you googled for something like javascript date validation? It shows up some good information, and a working code example here.

answered Nov 19, 2009 at 21:07

3 Comments

Sorry to be PITA, but if everyone was told to google it, there would be no need for this site. This site is for people to offer advice and code, not to just say google it!
Did I just say google it? Can't you see I gave him (a link to) a code example?
Also, Gary, don't you agree that some do need to be told to google a bit?
0

I suggest you a couple of solutions.

  1. guide the user input with a date picker. This way you can control the input format. jQueryui datepicker is a popular implementation.

  2. use a js library to manage datetime data type (not an actual datatype in Javascript!!). I suggest you date.js.

answered Mar 18, 2013 at 11:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.