Salmiakki
"Super salmiakki pastilleja", a special taste from Finland

Check for the truth of the Date

Use JavaScript to check the validity of a date given by a user (version 1.1).

Often web sites have a input field for some kind of date. Perhaps this can be a birth day to check that the user is old/young enough, expiry date for Visa and several others.

The purpose of this JavaScript function is to see if the given date truly exists.

As we know, all months does not have the same amount of days, thus all years does not have the same count for the days in February.

The “leap year” occurs every fourth year and has 29 days in February, as for the other three year in the interval, have 28 days.

Let us start by defining the count for each month on those three other years.

var monthLength = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

As you can see, the array has 12 elements as there is months in a year and each of them represents the maximum numbers of days in that month.

The year can be meant for the year of birth, registration year, etc. Some reasonable range has to be set. This is done by “yearRange” array.

Sometimes the year is referred only with two numbers. When this happens, we need to know the range where to place it in.

For example, given the year 96 would stand for 1996, but sometimes depending of the application, it might stand for 1096 or just 96. Therefore we need to know the prefix to use. Note that prefix distance from the beginning to the end can be 99 years at maximum.

var yearRange = new Array(1900, 2100);

var yearPrefix = new Array(1951, 2050);

Let us start the function definition as we have the prerequisites fulfilled.

The function is to be called with two parameters, element and separator. The first one is the absolute path of the element of which contents are to be tested. Separator can be slash if the date is in format 16/03/1998 or some similar. If separator is not set, a slash will be used.

function checkDate(element, separator) {

    // Default separator

    if (!separator)

        separator = "/";

In case that the type of the element is “text” or “textarea”, the value is relatively easy to fetch.

    if (element.type == "text" || element.type == "textarea") {

        var pizza = element.value.split(separator);

        if (pizza.length < 3)

            return false;

        var day = pizza[0];

        var month = pizza[1];

        var year = pizza[2];

    }

But what if the element is a type of “select-one”?

We shall assume that the first element, which is used to call this function, is the one which stands for the day.

When we have the ability to call the function with defining only one element to use, we need to track down the other required elements to create the date. To achieve this, we can assume that the day field has a name which might end in “_day”. This way we can arrange the order of the three different “select” fields. The one representing month will have the same prefix, as the day element in the name, but in the end “_month”. Year goes through the same formula.

    else if (element.type == "select-one") {

        var parts = element.name.split("_");

        var element_m = element.form[parts[0] + "_month"];

        var element_y = element.form[parts[0] + "_year"];

        var day = parseInt(element.options[element.options.selectedIndex].value);

        var month = parseInt(element_m.options[element_m.options.selectedIndex].value);

        var year = parseInt(element_y.options[element_y.options.selectedIndex].value);

    }

If the type of the element does not match the previous options, it will not be tested, thus the date is not valid.

    else {

        return false;

    }

A small sanity check, now when we are supposed to have all the variables set…

    // First check that all variables are set

    if (!day || !month || !year)
        return false;

Before going to any further on checking the numbers, we have one thing to do, to see if the year is marked only with two numbers.

    if (year.length != 2 && year.length != 4)

        return false;

    if (year.length == 2) {

        if (yearPrefix[0].toString().substr(2, 2) <= year)
            year = yearPrefix[0].toString().substr(0, 2) + year;
        else
            year = yearPrefix[1].toString().substr(0, 2) + year;
   }

Now see if the year is between the given range.

   if (year < yearRange[0])

       return false;

   if (year > yearRange[1])

       return false;

Leap year check and change of day count for February if needed. Note that the first element in the array is on the key 0, so therefore February is at the key number 1.

   // Check if we are on the leap year

   if (year%4 == 0)

      monthLength[1] = 29;

How is the situation with the number of the months? Always 12 there are, right?

   // Is the month correct?

   if (month < 1 || month > 12)

       return false;

Since we have gone already this far, it is about time to check the day count.

   // Is the day correct?

   if (day > monthLength[month-1])

       return false;

All checks done, date qualified.

   // So far seems ok...

   return true;

}

What about using this function?

It does not write anything to the user, just returns a boolean value. Below you can find an example how to call this function.

function runDateCheck(element) {

   if (!element)

      return false;

   if (checkDate(element, ".")) {

       element.style.backgroundColor = "White";

    }

   else {

       element.style.backgroundColor = "Red";

   }

}

Here the the element in question changes its background colour depending on the correctness of the date.

Well how to use this in a html page then?

Here is one way.

<input type="text" name="syntaika" onblur="runDateCheck(document.newmember.syntaika)" />

Good luck, with bad implementation of JavaScript support in browsers, you will need it.