21.5. Validating Date

After checking the format of the email address, we go on to validate the date contained in the birthday field. The isDateValid() function is used to do so. Its code is shown below:


(validateFormEg1.wmls)

function isDateValid(date)
{
  var mm = String.subString(date, 0, 2);
  var dd = String.subString(date, 2, 2);
  var yyyy = String.subString(date, 4, 4);

  mm = Lang.parseInt(mm);
  dd = Lang.parseInt(dd);
  yyyy = Lang.parseInt(yyyy);

  if (mm<1 || mm>12)
    return false;

  var maxDay = 31;
  if (4==mm || 6==mm || 9==mm || 11==mm)
    maxDay = 30;
  if (2==mm){
    if (0 == yyyy%4)
      maxDay = 29; // Leap year
    else
      maxDay = 28;
  }

  if (dd<1 || dd>maxDay)
    return false;

  return true;
}


Remember that in the earlier WML document, we have used the format attribute to set the input mask of the birthday field to be "NNNNNNNN". This input mask ensures that the birthday field contains 8 numeric characters. Hence, we do not check for this in the isDateValid() function.

At the start of the isDateValid() function, we make use of the subString() function of the String standard library to extract the month, day and year:


  var mm = String.subString(date, 0, 2);
  var dd = String.subString(date, 2, 2);
  var yyyy = String.subString(date, 4, 4);

The value returned from the subString() function is of the string type. We need to use the parseInt() function of the Lang standard library to convert them into the integer type so that we can perform comparisons and mathematical operations easily afterwards:


  mm = Lang.parseInt(mm);
  dd = Lang.parseInt(dd);
  yyyy = Lang.parseInt(yyyy);


Next we check the month value. If it is smaller than one or greater than twelve, it is not a valid month value.

After that we check the day value. April, June, September and November have 30 days. Other months have 31 days. February has 29 days in a leap year, otherwise it has 28 days. If the year value can be divided by 4, then it is a leap year. For example, 2004 can be divided by 4 and it is a leap year. If the day value is smaller than one or greater than the number of days in that month, it is not valid.


Previous Page Page 69 of 71 Next Page


Feedback Form (ExpandCollapse)

What do you think about this web page?






(Optional) Please provide us more details. For example, suppose you select option 2 above, can you tell us specifically what information is missing? You can also suggest anything that can help us improve this web page.

(Optional) Your name:

(Optional) Your email address:

Please enter again to confirm:

Due to the amount of messages we received, we may not be able to reply to all messages.

A button for going back to the top of this page