Wednesday 23 October 2013

A Simple Way to Compare Two Date Inputs Using JavaScript


A very sweet girlfriend of  mine, who is also into programming and other juicy IT packages, asked me to write a validation function for her company website. Aside from checking textboxes for empty strings and wrong data on the site, the function is also meant to do a comparison of 2 date inputs- date of birth and graduation date.

Ordinarily, if restrictions are not set during the design of web components on online applications, some site users can be so careless and annoying. Some persons might just want to test for the efficiency and validity of your site by entering conflicting data. Now, how would you handle all of those junks in the form of data if not for the help of validations? I presume much work for your database administrator, if you ask m.

So, it is so good a program practice, to create certain functions that will curb these malicious and frivolous data from your users. Pardon me if am being too crude here, its just how tidious site users has made our work as programmers to become.
Anyway, I am going to show you how to write a simple function into your HTML form (its actually a javascript code), that will check for, validate and compare certain data types and inputs from your users. My case study here is the date data type.

THE HTML FUNCTION

The first thing you are going to do is to create a simple HTML form. So, I am going to write a simple code for that, assuming you do not know how to.
Just fire up your favourite text editor, notepad or notepad++... I use the later because its so programmer friendly (code highlighting and specific language library, don't ask.)

So, here is the code you will use to create the HTML form:

<html>
          <head>
                    <title>Date Validation</title>
                    <h1>Date Validation Using Javascript</h1>
          </head>
          <body>
                      <form action="url" id="dateForm" onsubmit="return CheckEndDate()">
                    Date of Birth: <br>
                        <input type="date" id="Start" /><br>
                        <br>
                    Date of Graduation: <br>
                        <input type="date" id="End" /><br>
                        --------------------------<br>
                    <input type="submit" value="Submit" />
                    <input type="reset" value="Reset" />
                </form>
          </body>
</html>

For those familiar with the jargons I wrote above, you will understand that i just created a web form with two inputs and two event objects, a submit and a reset button. And if you noticed, the data type for the inputs are both date types. I did this so the users wont have to start typing wrong date formats. For some browsers like chrome and safari, the UI calender widget will pop out on clicking the boxes.

THE JAVASCRIPT DATE COMPARISON

Now, I am going to show you the next thing to do, which is to write a function for the date validations and comparison.
For corresspondence, just copy and paste the below code inbetween the head tag of your HTML form.

<script language="javascript" type="text/javascript">
           
                function CheckEndDate()
                {
               
                    Start=dateForm.Start.value;
                    if (Start=="" || Start==null){
                        alert ("Date of Birth cannot be empty");
                        dateForm.Start.focus();
                        return false;
                    }
                   
                    // checking for wrong date of birth
                    var today= new Date();
                    if (Start == today){
                        alert("Are you supposed to be born today?... Use your head oo.");
                        dateForm.Start.focus();
                        return false;
                    }
                   
                    //checking for empty graduation date text box
                    End=dateForm.End.value;
                    if (End=="" || End==null){
                        alert ("Graduation Year cannot be empty");
                        dateForm.End.focus();
                        return false;
                    }
                    //comparing both dates
                    var db_UTC = new Date(79,5,24); //this method converts the values to date for DOB
                    var gr_UTC = new Date(79,5,24);// this method converts the values to date for grad year
                    // converting dates to millisecond
                    db_UTC = Date.UTC( db_UTC.getFullYear (), db_UTC.getMonth(), db_UTC.getDate(),0,0,0,0);
                    gr_UTC = Date.UTC( gr_UTC.getFullYear (), gr_UTC.getMonth(), gr_UTC.getDate(),0,0,0,0);
                   
                     //first comparison: logical checking
                    if (db_UTC > gr_UTC){
                        alert("Oops!... Date of Graduation cannot be less than date of birth")
                        return false;
                    }
                    //second comparison: equality checking
                    else if (db_UTC == gr_UTC){
                        alert("Hmm... you no you can not graduate the same day you were born na. Haba!");
                        return false;
                    }
                   
                   
                }
                                   
</script>

if you have done this properly, you should have this out put:

<html>
<title> Date Validations With JavaScript</title>
    <head>
            <h1 align="center">Date Validations With JavaScript</h1><hr>
            <script language="javascript" type="text/javascript">
           
                function CheckEndDate()
                {
               
                    Start=dateForm.Start.value;
                    if (Start=="" || Start==null){
                        alert ("Date of Birth cannot be empty");
                        dateForm.Start.focus();
                        return false;
                    }
                   
                    // checking for wrong date of birth
                    var today= new Date();
                    if (Start == today){
                        alert("Are you supposed to be born today?... Use your head oo.");
                        dateForm.Start.focus();
                        return false;
                    }
                   
                    //checking for empty graduation date text box
                    End=dateForm.End.value;
                    if (End=="" || End==null){
                        alert ("Graduation Year cannot be empty");
                        dateForm.End.focus();
                        return false;
                    }
                    //comparing both dates
                    var db_UTC = new Date(79,5,24); //this method converts the values to date for DOB
                    var gr_UTC = new Date(79,5,24);// this method converts the values to date for grad year
                    // converting dates to millisecond
                    db_UTC = Date.UTC( db_UTC.getFullYear (), db_UTC.getMonth(), db_UTC.getDate(),0,0,0,0);
                    gr_UTC = Date.UTC( gr_UTC.getFullYear (), gr_UTC.getMonth(), gr_UTC.getDate(),0,0,0,0);
                   
                     //first comparison: logical checking
                    if (db_UTC > gr_UTC){
                        alert("Oops!... Date of Graduation cannot be less than date of birth")
                        return false;
                    }
                    //second comparison: equality checking
                    else if (db_UTC == gr_UTC){
                        alert("Hmm... you no you can not graduate the same day you were born na. Haba!");
                        return false;
                    }
                   
                   
                }
                                   
            </script>
    </head>
    <body>
       
                <form action="url" id="dateForm" onsubmit="return CheckEndDate()">
                    Date of Birth: <br>
                        <input type="date" id="Start" /><br>
                        <br>
                    Date of Graduation: <br>
                        <input type="date" id="End" /><br>
                        --------------------------<br>
                    <input type="submit" value="Submit" />
                    <input type="reset" value="Reset" />
                </form>
        </form>
    </body>
</html>

No comments:

Post a Comment

Tell me what you think...