Open Source Tutorials - Open Source Training
Open source training & tutorials from experienced, passionate people
chrome icon firefox icon ie icon opera icon safari icon Sings in these Browsers
A- A A+

By A Web Design

pdf icons text icons

Check that a date is valid according to month

Introduction:

Sometimes we want some date information from user (e.g. birth date, admission date), but it is not necessary that user will enter valid date that’s why we need to validate the date enter by user

As we see earlier first check is always empty field check, but here it is not needed to provide empty field check as we are using combo-box as data entry element.

In this example we are checking if date entered by user is valid according or not.

This example displays a form that requires a date chosen is correct or not before its dispatch to a Web server for further processing. The look and feel of the form is as shown in diagram 1.

diagram1.gif
Diagram1

The first snippet of code described is the HTML responsible for rendering the form in the visitor’s browser as shown in diagram 1.

If date choose is not proper and the Submit button is clicked an Alert will be displayed as shown in diagram 2.

diagram2.gif
Diagram2

HTML Code snippet

 
  <body onload="fillCombo();">
    <form name="frmTest" id="frmTest" method="post" action=""
    onsubmit="return validateTest(document.frmTest);">
      <table id="tblTest" width="">
        <tr>
          <td>Date of Birth</td>
          <td><select name="cmbDay" id="cmbDay" 
          value="" title="Day" /></select></td>
          <td><select name="cmbMonth" id="cmbMonth" 
          value="" title="Month" /></select></td>
          <td><select name="cmbYear" id="cmbYear" 
          value="" title="Year" /></select></td>
        </tr>
        <tr>
          <td> </td>
          <td>Day</td>
          <td>Month</td>
          <td>Year</td>
        </tr>
        <tr>
          <td> </td>
          <td colspan="3">
          <input type="submit" name="btnSubmit" 
          id="btnSubmit" value="Submit" />  
          <input type="reset" name="btnCancel" 
          id="btnCancel" value="Cancel" /></td>
        </tr>
      </table>
    </form>
  </body>
 

Elements used in the HTML code snippet are:

  1. Form
  2. Combo-box
  3. Button

Description of each element

  1. Form: A form object is defined in HTML between the <FORM></FORM> tags. The form object will normally enclose holds various data capture HTML elements like Textboxes, Textareas, Combo-boxes, Radio buttons, Checkboxes and so on
  2. Combo-box: It’s one of the many HTML data capture elements. It is used to capture text based, user data, but it is used for getting fixed input from user.
  3. Button: A button is considered an HTML data control element. It’s usually used to perform some sort of controlling action such as submitting the form data captured to a Web server for further processing, resetting the form data to datum and so on.

In the form frmTest the Javascript function validateTest(document.frmTest) is called when the Submit button is clicked. This is how that happens:

When the Submit button is clicked, the frmTest onsubmit method is automatically invoked which in turn invokes the Javascript function validateTest(); The form is passed to this Javascript function as the parameter - document.frmTest. Hence the function validateTest(); operates on document.frmTest.

It’s the signature of validateTest(); that tests if date is valid or not.

JAVASCRIPT Code Snippet

 
<script type="text/javascript">
 
  //Declaration of global variable starts
  //instantiate date object
  var objDate = new Date();
  //obtaining current year
  var strCurrentYear = objDate.getFullYear();
  //creating arrays of day, month and year
  var arrDay = new Array();
  var arrMonth = new Array();
  var arrYear = new Array();
  //We are limiting user to choose date before 50 years 
  //and after 50 years from current year
  var intLimiter = 50;
  //This function will fill comboboxes on a page load
 
  function fillCombo()
  {
    //Fill "day" combobox with day values
    for(var strValue=1;strValue <= 31;strValue++ )
    {
      addOption(document.frmTest.cmbDay, strValue, strValue);
    }
    //Fill "Month" combobox with Month values
    for(var strValue=1;strValue <= 12;strValue++ )
    {
      addOption(document.frmTest.cmbMonth, strValue, strValue);
    }
    //Fill "Year" combobox with Year values
    for(strValue=strCurrentYear- intLimiter;strValue <= strCurrentYear 
    + intLimiter;strValue++ )
    {
      addOption(document.frmTest.cmbYear, strValue, strValue);
    }
  }
 
 
  //This function will add options to combobox
  function addOption(selectbox,text,value )
  {
    //Create HTML element OPTION in DOM and store into an object 
    //named optn
    var optn = document.createElement("OPTION");
    //Assign value in a variable called text to text property of 
    //object optn(which is handle to OPTION element)
    optn.text = text;
    //Assign value in a variable called value to value property 
    //of object optn(which is handle to OPTION element)
    optn.value = value;
    //Append object to <SELECT> element
    selectbox.options.add(optn);
  }
 
  //This function checks leap year
  function checkLeap(year)
  {
    if (year%4==0)//e.g. years like 2004
    {
      return true
    }
    else
    {
      return false;
    }
  }
 
  //validating a user's date
  function validateTest(objFrm)
  {
    //set types of the month according to number of days
    //for months jan,mar,may,july,aug,oct,dec
    var highestDayType1 = 31 ; 
    //for months apr,june,sept,nov
    var highestDayType2 = 30 ; 
    //for month feb
    var highestDayType3 = 28 ; 
    //for month feb with leap year
    var highestDayType4 = 29 ; 
    //check variable
    var dayInTheMonthChecker= "" ; 
    //set leap year variable to false
    //obtaining day, month , year values from user
    var leapYear=false ; 
    var strUserDay=objFrm.cmbDay.value;
    var strUserMonth=objFrm.cmbMonth.value;
    var strUserYear=objFrm.cmbYear.value;
 
    //check if year is leap or not
    if(checkLeap(strUserYear))
    {
      leapYear = true;//set leap year variable to true
    }
 
    //set check variable dayInTheMonthChecker's value according 
    //to month value choose by user
    if(objFrm.cmbMonth.value=="1" || objFrm.cmbMonth.value=="3" 
    || objFrm.cmbMonth.value=="5" ||
    objFrm.cmbMonth.value=="7" || objFrm.cmbMonth.value=="8" 
    || objFrm.cmbMonth.value=="10" ||
    objFrm.cmbMonth.value=="12")
    {
      dayInTheMonthChecker = highestDayType1;//set check varaible 
      //to value of highestDayType1
    }
    else if(objFrm.cmbMonth.value=="4" || objFrm.cmbMonth.value=="6" 
    || objFrm.cmbMonth.value=="9"
    || objFrm.cmbMonth.value=="11")
    {
      dayInTheMonthChecker = highestDayType2;//set check varaible to 
      //value of highestDayType2
    }
    else if(objFrm.cmbMonth.value=="2" && leapYear==false)
    {
      dayInTheMonthChecker = highestDayType3;//set check varaible to 
      //value of highestDayType3
    }
    else if(objFrm.cmbMonth.value=="2" && leapYear==true)
    {
      dayInTheMonthChecker = highestDayType4;//set check varaible to 
      //value of highestDayType4
    }
    //checking valid day for the month
    if(strUserDay > dayInTheMonthChecker) //if day value choose by 
    //user is beyond particular month's limit
    {
      alert("Date you have choose is invalid");//pop an alert
      return false; //The value false is returned to the function 
      //so that form submission aborted
    }
    else
    {
      return true; 
      //The value false is returned to the function so that form 
      //submission done
    }
  }
</script>
 

NOTE: While Javascript code can be included anywhere in the HTML codespec it is prudent that Javascript is always written within the <HEAD></HEAD> HTML tags.

To separate Javascript code from HTML code it is always placed within the <script></script> that are normally placed within <HEAD></HEAD> HTML tags.

The <SCRIPT> tag has following attributes:
type: It specifies MIME type of script
src: Specifies the URL of an external Javascript file if one is used

Working of the Javascript code:

  1. In this Javascript code we declare variables out of functions so it can be accessible by multiple functions and their scope is script wide.
  2. //Declaration of global variable starts
    //instantiate date object
    var objDate = new Date();
    //obtaining current year
    var strCurrentYear = objDate.getFullYear();
    //creating arrays of day, month and year
    var arrDay = new Array();
    var arrMonth = new Array();
    var arrYear = new Array();
    //We are limiting user to choose date before 50 years and after 50 years from current year
    var intLimiter = 50;

  1. The Javascript code contains multiple functions where one function is calling other and vice versa
  2. function fillCombo()//fills combobox of day,month, year on page load
    function addOption(selectbox,text,value )//add options to combobox
    function checkLeap(year)//checks if selected year is leap or not
    function validateTest(objFrm)//validate date choose by user

  1. First fillCombo() function is called, which fills the combo-boxes of day, month and year
  1. fillCombo calls another function addOption(selectbox,text,value ) which creates an option element and filled it with day, months and years value
  1. Third function is checkLeap(year), which checks if year chose by user is leap year or not, if year is divisible by 4 then it is considered as leap year and function returns true value else function returns false
  1. Fourth function validateTest() is validate date by compare it with certain criteria, it is multi-step process; steps involved in it are as follows
  1. First categorize all months according to number of days in it i.e. 31,30,29,28 ; create four variables to store these different types of months
    1. var highestDayType1 = 31 ;//for months jan,mar,may,july,aug,oct,dec
    2. var highestDayType1 = 31 ;//for months jan,mar,may,july,aug,oct,dec
    3. var highestDayType2 = 30 ;//for months apr,june,sept,nov
    4. var highestDayType3 = 28 ;//for month feb
    5. var highestDayType4 = 29 ;//for month feb with leap year
  1. Create check variable dayInTheMonthChecker (which will use for storing days in the month later) and set it to null or blank
  1. Set Boolean variable leapYear to false
  1. Accept day,month and year from user and store it in different variables
    1. //obtaining day, month , year values from user
    2. var strUserDay=objFrm.cmbDay.value;
    3. var strUserMonth=objFrm.cmbMonth.value;
    4. var strUserYear=objFrm.cmbYear.value;
  1. Check if year is leap or not, if year is leap then set leapYear Boolean variable to true
    //check if year is leap or not

    if(checkLeap(strUserYear))
    {
    leapYear = true;//set leap year variable to true
    }

  1. set check variable dayInTheMonthChecker's value equal to month value choose by user
  2. if(objFrm.cmbMonth.value=="1" || objFrm.cmbMonth.value=="3" || objFrm.cmbMonth.value=="5" || objFrm.cmbMonth.value=="7" || objFrm.cmbMonth.value=="8" || objFrm.cmbMonth.value=="10" || objFrm.cmbMonth.value=="12")
    {
    dayInTheMonthChecker = highestDayType1;//set check varaible to value of highestDayType1
    }
    else if(objFrm.cmbMonth.value=="4" || objFrm.cmbMonth.value=="6" || objFrm.cmbMonth.value=="9" || objFrm.cmbMonth.value=="11")
    {
    dayInTheMonthChecker = highestDayType2;//set check varaible to value of highestDayType2
    }
    else if(objFrm.cmbMonth.value=="2" && leapYear==false)
    {
    dayInTheMonthChecker = highestDayType3;//set check varaible to value of highestDayType3
    }
    else if(objFrm.cmbMonth.value=="2" && leapYear==true)
    {
    dayInTheMonthChecker = highestDayType4;//set check varaible to value of highestDayType4
    }

  1. Now validate the user date by comparing it with check variable dayInTheMonthChecker, if user date is greater than value store in check variable then an Alert is popped up to catch the users attention and display an appropriate error message for the user to read

alert("Date you have choose is invalid");

  1. Since an Alert is a modal window all processing will stop until the User responds to the Alert by clicking on the Alert’s Ok button
  1. If all conditions are valid (i.e. date is perfect), then control will pass to else block of the if condition. This will return the value TRUE to the onsubmit method of the form object and the form’s contents will get submitted to the Web server for further processing.
  1. NOTE: In this specific case nothing else will happen because the form’s ACTION attribute is loaded with the # symbol. Normally value passed to the ACTION attribute of the form is the name of the program at the Web server that will process the data submitted by the form to the Web server. In this case since the ACTION attribute holds # the Web server will receive the data submitted by the form by will do nothing further.

The Complete Code snippet

 
<html>
  <head>
  <title> Date Validation </title>
  <style>
  body
  {
  font-family:Tahoma,Verdana, Arial, Helvetica, sans-serif;
  font-size:9pt;
  color:#000000;
  }
  </style>
 
  <script type="text/javascript">
 
  //instantiate date object
  var objDate = new Date();
  //obtaining current year
  var strCurrentYear = objDate.getFullYear();
  //creating arrays of day, month and year
  var arrDay = new Array();
  var arrMonth = new Array();
  var arrYear = new Array();
  //We are limiting user to choose date before 50 years and after 
  50 years from current year
  var intLimiter = 50;
  //This function will fill comboboxes on a page load
 
  function fillCombo()
  {
    //Fill "day" combobox with day values
    for(var strValue=1;strValue <= 31;strValue++ )
    {
      addOption(document.frmTest.cmbDay, strValue, strValue);
    }
    //Fill "Month" combobox with Month values
    for(var strValue=1;strValue <= 12;strValue++ )
    {
      addOption(document.frmTest.cmbMonth, strValue, strValue);
    }
    //Fill "Year" combobox with Year values
    for(strValue=strCurrentYear- intLimiter;strValue <= strCurrentYear 
    + intLimiter;strValue++ )
    {
      addOption(document.frmTest.cmbYear, strValue, strValue);
    }
  }
  //This function will add options to combobox
  function addOption(selectbox,text,value )
  {
    //Create HTML element OPTION in DOM and store into an object 
    //named optn
    var optn = document.createElement("OPTION");
    //Assign value in a variable called text to text property of object 
    //optn(which is handle to OPTION element)
    optn.text = text;
    //Assign value in a variable called value to value property of 
    //object optn(which is handle to OPTION element)
    optn.value = value;
    //Append object to <SELECT> element
    selectbox.options.add(optn);
    }
    //This function checks leap year
    function checkLeap(year)
    {
    if (year%4==0)//e.g. years like 2004
    {
      return true
    }
    else
    {
      return false;
    }
  }
 
  //validating a user's date
  function validateTest(objFrm)
  {
    //set types of the month according to number of days
    var highestDayType1 = 31 ;//for months jan,mar,may,july,aug,oct,dec
    var highestDayType2 = 30 ;//for months apr,june,sept,nov
    var highestDayType3 = 28 ;//for month feb
    var highestDayType4 = 29 ;//for month feb with leap year
    var dayInTheMonthChecker= "" ;//check variable
    var leapYear=false ;//set leap year variable to false
    //obtaining day, month , year values from user
    var strUserDay=objFrm.cmbDay.value;
    var strUserMonth=objFrm.cmbMonth.value;
    var strUserYear=objFrm.cmbYear.value;
 
    //check if year is leap or not
    if(checkLeap(strUserYear))
    {
      leapYear = true;//set leap year variable to true
    }//set check variable dayInTheMonthChecker's value according to 
    //month value choose by user
 
    if(objFrm.cmbMonth.value=="1" || objFrm.cmbMonth.value=="3" ||
    objFrm.cmbMonth.value=="5" || objFrm.cmbMonth.value=="7" || 
    objFrm.cmbMonth.value=="8"|| objFrm.cmbMonth.value=="10" || 
    objFrm.cmbMonth.value=="12")
    {
      dayInTheMonthChecker = highestDayType1;//set check varaible 
      //to value of highestDayType1
    }
    else if(objFrm.cmbMonth.value=="4" || objFrm.cmbMonth.value=="6" ||
    objFrm.cmbMonth.value=="9" || objFrm.cmbMonth.value=="11")
    {
      dayInTheMonthChecker = highestDayType2;//set check varaible 
      //to value of highestDayType2
    }
    else if(objFrm.cmbMonth.value=="2" && leapYear==false)
    {
      dayInTheMonthChecker = highestDayType3;//set check varaible 
      //to value of highestDayType3
    }
    else if(objFrm.cmbMonth.value=="2" && leapYear==true)
    {
      dayInTheMonthChecker = highestDayType4;//set check varaible 
      //to value of highestDayType4
    }
 
    //checking valid day for the month
    if(strUserDay > dayInTheMonthChecker)//if day value choose by user 
    //is beyond particular month's limit
    {
      alert("Date you have choose is invalid");
      // An alert box is popped up in the browser if it is with 
      //a message in it
      return false;
      //The value false is returned to the function so that form 
      //submission aborted
    }
    else
    {
      return true; //The value false is returned to the function so 
      //that form submission done
    }
  }
  </script>
  </head>
 
  <body onload="fillCombo();">
    <form name="frmTest" id="frmTest" method="post" action=""
    onsubmit="return validateTest(document.frmTest);">
      <table id="tblTest" width="">
        <tr>
          <td>Date of Birth</td>
          <td><select name="cmbDay" id="cmbDay" value="" 
          title="Day" /></select></td>
          <td><select name="cmbMonth" id="cmbMonth" value="" 
          title="Month" /></select></td>
          <td><select name="cmbYear" id="cmbYear" value="" 
          title="Year" /></select></td>
        </tr>
        <tr>
          <td> </td>
          <td>Day</td>
          <td>Month</td>
          <td>Year</td>
        </tr>
        <tr>
          <td> </td>
          <td colspan="3">
          <input type="submit" name="btnSubmit" id="btnSubmit" 
          value="Submit" />  
          <input type="reset" name="btnCancel" id="btnCancel" 
          value="Cancel" /></td>
        </tr>
      </table>
    </form>
  </body>
</html>
 
OSV Newsletter


Receive HTML?

NOTE: To prevent subscription to the OSV newsletter, uncheck the checkbox above.
Guest Blog for OSV
Free Ebook Download
LinkShare_180x150
Artisteer - DNN Skin Generator
Tapestry Theme - A Tumblog-Style Theme for Wordpress