Using javascript and a custom validator to check the start and end dates of a date?

I am trying to check the start date and end date so that if the end date entered by the user is before the start date, it will cause an error. I do this using JavaScript and a custom validator, but I get a runtime error: "CheckDate is undefined".

I think this should not be difficult to solve, since the code looks fine, I just missed something.

Any help would be great.

Here is my javascript, it just didn’t copy them in script tags

function CheckDate(sender, args) { if (new date (document.getElementById("txtstartdate").value) > new (document.getElementById("TxtFinish").value)) { args.IsValid = false; return; } args.IsValid = true; } 

Here is a check on my FinishDate control

 <asp:CustomValidator ID="CustomValidator29" runat="server" ErrorMessage="Finish Date should be greater than the Start Date" ClientValidationFunction="CheckDate"></asp:CustomValidator> 

You need more information to ask :).

+4
source share
2 answers

You can just use CompareValidator!

  <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="txtStartDate" ControlToValidate="txtEndDate" Display="Static" ErrorMessage="'End Date' must not be earlier than 'From Date'" Text="*" Operator="GreaterThanEqual" SetFocusOnError="True" Type="Date" ValidationGroup="SearchGroup"> 

+5
source

Here is what I did, and it is being tested perfectly. Since I didn’t know exactly which control you used, I simply used the base text box. I would introduce values ​​such as "July 21, 1983 01:15:00."

JavaScript:

 <script type="text/javascript" > function CheckDate(sender, args) { var startDate = new Date(document.getElementById("txtStartDate").value); var finishDate = new Date(document.getElementById("txtFinishDate").value); if (startDate > finishDate) { args.IsValid = false; } else { args.IsValid = true; } } </script> 

HTML:

 <asp:CustomValidator ID="CustomValidator29" runat="server" ErrorMessage="Finish Date should be greater than the Start Date" ClientValidationFunction="CheckDate" ControlToValidate="txtStartDate"> </asp:CustomValidator> <asp:TextBox id="txtStartDate" runat="server" /> <asp:TextBox id="txtFinishDate" runat="server" /> 

Here is a table of values ​​and results:

txtStartDate: July 21, 1983 01:15:00
txtEndDate: July 25, 1983 01:15:00
Valid: Yes

txtStartDate: July 25, 1983 01:15:00
txtEndDate: July 21, 1983 01:15:00
Valid: No

txtStartDate: July 21, 1983 01:15:00
txtEndDate: July 21, 1983 06:15:00
Valid: Yes

txtStartDate: July 21, 1983 06:15:00
txtEndDate: July 21, 1983 01:15:00
Valid: No

+1
source

Source: https://habr.com/ru/post/1432069/


All Articles