tabs

Monday, November 11, 2013

How to check date is greater or lesser than Current Date using javascript / jQuery

"This post is all about to check whether the entered date is less than or greater than the current date using jquery/javascript"
This is one of the most common scenarios we come across in most of the applications in our daily life. Selecting a date is quite a common thing or most of the times a mandatory field in our applications. The date field is used in all utilities starting from a simple application form for a school child to transactions form of a bank. But sometimes we are asked to set some validations on the date field, say to check whether the entered date is greater or lesser than the current date.
So in this post we implement a very useful validation on date field. Generally we use a date-picker to help user to select a date.But in our case we just use a textbox and enter the date in a particular format. Sometimes we come across a requirement to check that the date entered by the user should not be greater than the current date or sometimes greater than the current date.
So let us move further on how to implement this using a bit of JavaScript or jQuery. Suppose we have a couple of fields with a submit button in our page.

        Name:<input type="text" id="txtName" />
        DOB:<input type="text" id="txtDateEntered" />
        <input type="submit" id="Text1" onclick="compareDate();"/>
Note:Date should be entered in this format [dd-mm-yyyy]. Now here goes the JavaScript code on how to check whether the entered date is greater or lesser than the current date. In my JavaScripr file:
function compareDate() {
    //In javascript
    var dateEntered = document.getElementById("txtDateEntered").value; 
    // In JQuery
    var dateEntered = $("#txtDateEntered").val();
 
    var date = dateEntered.substring(0, 2);
    var month = dateEntered.substring(3, 5);
    var year = dateEntered.substring(6, 10);
 
    var dateToCompare = new Date(year, month - 1, date);
    var currentDate = new Date();
 
    if (dateToCompare > currentDate) {
        alert("Date Entered is greater than Current Date ");
    }
    else {
        alert("Date Entered is lesser than Current Date");
    }
}

This is how you check whether the entered date is greater or lesser than the current date. That’s all the simple script above does the trick for you. So try to follow the code given above and implement wherever you require.
Hope it helps you and feel free to suggest or post comments.
For more knowledge on jQuery/JavaScript ,you can explore Tricks in jQuery/JavaScript.

No comments:

Post a Comment