During the development process of an ASP.NET website, we face an issue of comparing date values entered by user and validating them so that no logical error occurs. This case mostly happens when we have two date values to be supplied and the first value for sure must be less than the second one. As an example, an event may have two date values which are Start Date and End Date where the End Date value must be greater than the Start Date to prevent any further conflict when these values are used later on.
The comparison and validation process can take place either at the server side when an event is fired (postback) in the webpage (comparing values using C# or VB in the code behind), or at the client side using Javascript or jQuery.
Our method is based on using ASP.NET controls for validation and comparison, and this takes place at the client side when these controls are rendered as HTML and scripts inside the page displayed to the client and before posting back the page to the server.
Consider the example below showing how we can apply this method:
<asp:Calendar ID="calStartDate" runat="server"></asp:Calendar> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="calStartDate" ErrorMessage='Start Date Required' Display="Dynamic" Font-Bold="true" ForeColor="Red"></asp:RequiredFieldValidator> <asp:Calendar ID="calEndDate" runat="server"></asp:Calendar> <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="calEndDate" ErrorMessage='End Date Required' Display="Dynamic" Font-Bold="true" ForeColor="Red"></asp:RequiredFieldValidator> <asp:CompareValidator ID="CompareValidator1" runat="server" Operator="GreaterThan" ControlToValidate="calEndDate" ControlToCompare="calStartDate" ErrorMessage='End Date must be greater than Start Date' Font-Bold="true" ForeColor="Red"></asp:CompareValidator>
The ASP.NET RequiredFieldValidator is used to indicate that the target field is a required field where no action can take place without providing a value for this field, so by using this control we can ensure that the Calender control for both Start Date and End Date are not left empty.
The ASP.NET CompareValidator is used to compare two controls values together according to the kind of operation decided inside its Operator parameter. In the example above, we’re using the GreaterThan so that we can ensure that the End Date is greater than the Start Date.
If the End Date isn’t greater than the Start Date, then the error message will be displayed beside the control and preventing the page from posting the page back to the server.
Note that, in order to achieve the comparison and validation process by rising any event inside the page like a button click, the control related to the event fired should be set to cause validation by using: CausesValidation=”true”.
Awesome Article!