Home > Abakada: Back to Basics > Basic Scripting > Data Entry Validation > Checking for valid date input
Abakada ~ Back to Basics
The following is a sample validation routine that checks for a valid date value from a text field entry.
Enter any date in m/d/y or m-d-y short date format, or in long date format as in '25 May 2000', which can be entered with the year, month, and day in any order.
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 instance of time, or is not valid as a date value. The above form's validation handler uses isNaN to check this return value.
Now let's explore how that is done.
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 "Jan 15 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
.
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
.
The code for that exercise is as follows:
<form name="theForm" onsubmit="return getDateDemo ( )">
<input name="dater">
<input type="submit" value="Get Date">
</form>
<script language="JavaScript">
<!--
function getDateDemo ( ) {
var d = document.theForm.dater.value;
d = new Date ( d );
if ( isNaN ( d ) ) {
alert ( 'Sorry, not a valid date' );
document.theForm.dater.select ( );
document.theForm.dater.focus ( );
return false
}
alert ( d );
return true;
}
//-->
</script>
In actual use, the alert after a valid input is not necessary. It is just there to show that a Date object is indeed returned if successful.
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 parse method, it will successfully be converted to a valid Date object.
Enter your birthday and see what day you were born.
Validating Against a Data Type ( Web Forms ) Web Forms Validation