Chitika

Saturday, March 23, 2013

Restrict user to enter past/previous dates using javascript

When we are working with dates by taking input from the user it is always required to restrict the user to enter the past/previous dates.
We can achieve this by using JavaScript.

Now first take one input box and button, in asp.net we use text box and button as below,

<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
 <asp:Button ID="btnSubmit" runat="server" Text="Save" OnClientClick="return checkdate(txtDate);" />

If you want to use HTML controls use below code,
 <input type="text" name="txtDate" />
  <input type="submit" value="Submit" onclick="return checkdate(txtDate);" />

Next we need to write the JavaScript to check the date, see the script below,

 <script type="text/javascript">
        function checkdate(txt) {
            var selectedDate = new Date(txt.value);
            var today = new Date();
            today.setHours(0, 0, 0, 0);
            if (selectedDate < today) {
                alert('Past Dates are not allowed.');
                txt.value = '';
            }
        } 
    </script>

You can observe the above code we are checking the entered date on button click.
You can also write the same in onblur or onchange of the textbox .

In the above example we are restricting the user to enter the date less than today's date.
It depends on the your requirement up to which date we need to restrict.

See more articles on  JavaScript 

No comments:

Post a Comment