faqts : Computers : Programming : Languages : JavaScript : Forms

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

53 of 73 people (73%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I check for a valid date input?
How can a text field entry be checked for valid date values?

Aug 27th, 2000 04:48
Rey Nuņez, http://msdn.microsoft.com/scripting/jscript/doc/jsmthparse.htm


In cases where a string input is given for date values, as in a text 
box, the string is parsed according to the rules in the Date.parse() 
method. 

There are several rules that govern what the parse() method can 
successfully parse, the more important of which are: 

- Short dates can use either a '/' or '-' date separator, but must 
follow the month/day/year format, for example "8/15/2000". 

- Long dates of the form "July 10 1995" can be given with the year, 
month, and day in any order, and the year in 2-digit or 4-digit form. 
If you use the 2-digit form, the year must be greater than or equal to 
70. 

Here is an example of getting a Date object from user input. Enter any 
date in m/d/y or m-d-y format, or in long date format as mentioned 
above. 
 
<div align="center">
<form name="form">
<input name="dater"> <input type="button" value="Get Date" 
onclick="getDateDemo()">
</form>
</div>

<script language="JavaScript">
<!-- 
function getDateDemo(){
  var d = document.form.dater.value;
  d = new Date(d);
  if (!isNaN(d)) alert (d)
  else alert ('Sorry, not a valid date')
}
// -->
</script>

If the input is valid, a Date object is successfully returned. If the 
function returns NaN, it indicates that the object does not represent a 
specific instant of time, or is not valid as a date value. The above 
form's validation handler uses thw isNaN method to test this return 
value.

Note that if the value of an argument is greater than its range or is a 
negative number, the stored values are modified accordingly. For 
example, if you specify 6-45-2000, JavaScript redefines that number as 
7-15-2000. 

Here is another sample that gets the day of week from a given text 
input. As long as the input is valid according to the rules of the 
Date.parse() method, it will successfully be converted to a valid Date 
object. 

<div align="center">
<form name="dow">
<input name="dater"> <input type="button" value="Get Day" 
onclick="getDOW()">
</form>
</div>

<script language="JavaScript">
<!--
function getDOW(){
  var day, d = document.dow.dater.value;
  d = new Date(d)
  day = new Array
('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Satu
rday');
  x = d.getDay();
  if (!isNaN(d)) alert (day[x]);
  else alert ('Sorry, not a valid date')
}
//-->
</script> 

Enter your birthday and see what day you were born.