posted 2/13/2009 by Vijendra Shakya
Many times users are facing the problem to validate the date from Javascript.Here we discuss to validate date.I have Two text box for start date and end date now we validate end date always greater than start date. Following is the Javascript code to validate the date.
Html code of the textboxex are:
<table> <tr> <td> Start date:</td> <td> <input name="start-date" id="txtStartDate" runat="server" text="- min date" class="date-pick textBox-date" /> </td> </tr> <tr> <td> End date:</td> <td> <input name="end-date" id="txtEndDate" text="- max date" runat="server" class="date-pick textBox-date" /> </td> </tr> </table>
Javascript code is:
<script type="text/javascript">function CompareDate() { var fromDate = documet.getElementById('txtFromDate').value; var toDate = documet.getElementById('txtToDate').value; var endDate = new Date(toDate); var startDate = new Date(fromDate); if(fromDate!=''&&toDate!=''&&startDate>endDate) { alert('end date should be greater than or equal to start date'); documet.getElementById('txtToDate').value=""; return false; } else if(fromDate=='') { alert('Please enter start date!'); return false; } else if(toDate=='') { alert('Please enter end date!'); return false; } }</script>
if(fromDate!=''&&toDate!=''&&startDate>endDate) { alert('end date should be greater than or equal to start date'); documet.getElementById('txtToDate').value=""; return false; } else if(fromDate=='') { alert('Please enter start date!'); return false; } else if(toDate=='') { alert('Please enter end date!'); return false; } }</script>
Following is the server side validation to compare two date for that we use CompareValidator.
<asp:CompareValidator ID="cmpDate" runat="server" ControlToCompare="txtToDate" ControlToValidate="txtFromDate"Operator="GreaterThanEqual" Type="Date" Display="Dyanmic" ErrorMessage="End date should be greater than Start date"></asp:CompareValidator>
Here Type is the main propert to validate two date.Cheers!
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18