How can I utilize custom validators with JavaScript to validate the start and end dates?

I need to ensure that a user cannot enter a finish date before the start date in a form validation process. I am writing JavaScript code with a custom validator, but I keep encountering a runtime error stating 'CheckDate is undefined'.

Although my code seems correct, there might be something small that I am missing. Any assistance would be greatly appreciated.

Below is the JavaScript code written within script tags:

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

This is how I have set up the validation for the Finish Date control:

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

If you require any further information, feel free to ask :).

Answer №1

You have the option of utilizing a CompareValidator for this task!

  <asp:CompareValidator ID="CompareValidator2" runat="server" 
    ControlToCompare="txtStartDate" ControlToValidate="txtEndDate" 
    Display="Static" ErrorMessage="'End Date' should not be before 'Start Date'" Text="*"
    Operator="GreaterThanOrEqualTo" SetFocusOnError="True" Type="Date" 
    ValidationGroup="SearchCriteria">

Answer №2

Here is my solution, which has been successfully validated. I used a simple text box as I was unsure of the control you were using. Input values like "July 21, 1983 01:15:00".

JavaScript:

<script type="text/javascript" >

        function ValidateDate(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 must be after Start Date" 
    ClientValidationFunction="ValidateDate" ControlToValidate="txtStartDate">
</asp:CustomValidator>

<asp:TextBox id="txtStartDate" runat="server" />
<asp:TextBox id="txtFinishDate" runat="server" />

Below are example 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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Convert specific form inputs into an array

I have a form that includes various inputs, but the ones I am focusing on are labeled attributes[] and options[$index][]. Here is an example of the data found in my attributes[] input: Array ( [0] => Size [1] => Color [2] => Material ) Not ...

Developing JavaScript functionality to manage multiple radio buttons that should be hidden after being selected

I am currently in the process of building a comprehensive form that includes numerous radio buttons. My goal is to present one question at a time, which means using JavaScript to hide the respective div after a radio button has been clicked. While I have ...

Two distinct iterations of the identical jquery version sourced from external sources

NOTE: This situation involves having two copies of jQuery with the same version number but different libraries loaded by external sources. This is distinct from the issue of using multiple versions of jQuery on a single page, as discussed here: Can I use m ...

Refreshing the page triggers the callback function that retrieves the checkboxes selected in a Kendo treeview component

How can I retain the selected checkboxes after refreshing the page? Is there a way to achieve this using AJAX when submitting data to a database and then reloading the page? AJAX //AJAX call for button $("#primaryTextButton").kendoButton(); va ...

The functionality of react-waypoint's onEnter/onLeave event handlers seems to be malfunctioning

Recently, I experimented with react-waypoint to control the visibility of a div. The code works as intended by hiding the div when it reaches the waypoint inside onEnter. When the div is inside, the isInView state becomes true, which in turn triggers the d ...

Avoid duplicating content when using Ajax to retrieve data in jQuery

Is there a solution when you click the button to display content, then click the button to hide it, and then click the button again to show it repeatedly? I'm not sure how to solve this issue. Can anyone help me out? Thank you! Here is the HTML code: ...

The ReferenceArrayInput request is lacking an api-prefix

I have been attempting to utilize the ReferenceArrayInput component from react-admin in order to modify a OneToMany relationship. Although the options for the multi-select input load correctly, the actual selection does not work as expected. Interesting ...

Nextjs - resolving the issue of shopping carts displaying incorrect total amounts

I am currently facing an issue with the total cart amount while building a shopping cart. The problem arises when I visit the cart page as it only displays the amount of the last item added to the cart. state = { cart: { items: [], total: 0 }, }; ad ...

Is it possible to use Markdown in JavaScript without needing to enclose it in <p>

Is there a way to convert markdown text to HTML using JS libraries like markdown-js or marked without wrapping it in paragraph tags? For instance, I want to change this *italic* text to this <i>italic</i> text without including it within <p ...

Exploring the World of ASP.net VB Timers

I am looking for a way to measure page load time in ASP.net (VBscript). While adding Trace="true" to the page directive is helpful, I need to actually time an event and save it in a variable. In ASP, this was simple with the Timer object, but I am having ...

Transfer your focus to the following control by pressing the Enter key

I came across a project built on Angular 1.x that allows users to move focus to the next control by pressing the Enter key. 'use strict'; app.directive('setTabEnter', function () { var includeTags = ['INPUT', 'SELEC ...

Steps for passing a MVC Model in an Ajax Request

I am currently encountering some difficulties when attempting to post a Model to trigger an action in a controller. Within my main view, I initiate a web service call with specific criteria and receive the results. Once I have the results, I display them ...

Function call contains an undefined parameter

When working with my Vuex store, I encounter a problem in the action section. The code snippet in question is as follows: actionSignUp({ commit, dispatch }, form) { commit("setStatus", "loading") auth.createUserWithEmailAndPasswor ...

Exploring the use of Shadow DOM in ContentEditable for securing text segments

I have recently been working on creating a basic text editor using ContentEditable. The main requirement for the application is to allow users to insert blocks of text that are protected from typical editing actions. These protected text blocks should not ...

AngularJS enables the creation of multiselectable dropdown checkboxes

I am looking to create a dropdown list of checkboxes that allows for multiple selections. I have attempted to implement the code below, but I am facing an issue where the template refreshes each time a checkbox is clicked, preventing me from making multi ...

Transferring a JSON Object and a Group of Objects to an ASP.Net Controller

Could someone assist me with the code below please? I have two models and a method in which I will be utilizing them as shown below. public class RoleModel { public string Name { get; set; } public string Description { get; set; } public List& ...

Communication between nodes using serial ports in Node.js fails to receive a response from the connected Arduino board

I've been attempting to establish communication between a computer and an Arduino board using node.js. Despite having a simple program, it just doesn't seem to work as expected. The Arduino program (which seems to be working fine) is as follows: ...

Creating a dynamic list filter using JavaScript and three select boxes

Looking for a way to implement a similar feature to the one on this webpage: I will be showcasing a list of brands on the page, with each brand requiring three pieces of information: Starting letter Store (multiple options) Category (multiple options) ...

Using Three.js to display a PerspectiveCamera with a visible bounding Sphere

My challenge is to create a Scene that loads a single .obj file where the object is fully visible in the PerspectiveCamera upon scene initialization. The field of view (FOV) is set at 60 The objects vary in size TrackballControls are utilized for camera ...

I'm looking to switch out the `~` to turn it into a URL for the backend, seeing as `<img alt="" src="~/media/Banner/plane.JPG">` is returning a 404 error

1. Received an HTTP Request and JSON response from the backend localhost:3000 (entered value using wysiwyg) { "Description": "&lt;img alt=&quot;&quot; src=&quot;~/media/Banner/plane.JPG&quot; /&gt;1 test berita&lt ...