You can't just ignore invalid input by the user. Validation can be done either at client side or at server side. But with client side scripting, you can verify the input as quickly as possible without causing precious trips to the server.
Some types of input are very frequent. An email address is one such example. Getting date from the user is another. But to check the validity of an entered date, you are required to check a lot of things, including day of the month, month, leap year, etc. For example, 30th February is an invalid date and so is 29th February if we have a non-leap year. This article discusses date validation in detail.
Basic Framework:
We will write a function, validateDate(strDate), that accepts a date as a string and returns a true or false value. We will also be assuming that the date string will have the following format: MM-DD-YYYY. If you want to implement a different format, you will have to slightly change the function presented here.
The basic idea is quite simple. JavaScript provides a built in Date class. An object of this class can be constructed by providing a date string with the above discussed format. There is a problem with it, however. JavaScript will construct an object of this type even if the given date is invalid.
var objDate = new Date ("12-1-2001"); will create a date object that represents 1st of December 2001. On the other hand, var objDate = new Date ("13-1-2001") is an invalid date. But the object will be created representing 1st of January 2002.
Code:
<html>
<head>
<script language="JavaScript1.2">
function validateDate (strDate) {
var parsedDate = strDate.split ("-");
if (parsedDate.length != 3) return false;
var day, month, year;
month = parsedDate[0]-1;
day = parsedDate[1];
year = parsedDate[2];
var objDate = new Date (strDate);
if (month != objDate.getMonth()) return false;
if (day != objDate.getDate()) return false;
if (year != objDate.getFullYear()) return false;
return true;
}
var myDate = "13-1-2001";
if (validateDate (myDate) != true)
alert ("Invalid date.");
else
alert ("Date is valid.");
</script>
</head>
<body></body>
</html>
Explanation:
The function uses a simple technique to extract month, day and year components of the string "mm-dd-yyyy". You can use the split method of String class to break up a string with respect to a splitter. We have used - character to extract the three different parts. The result of this method is an array of strings.
Next, a date object is created as explained above. Since the newly created date object will always be a valid one, we call the methods getDate(), getMonth() and getFullYear() to get back the date, month and year. These are checked with the ones given in the string. A false value is returned if any of them does not match. A true is returned only when all the values match.
Go To Page: 1 2