The date function seems to be malfunctioning

In my ASP web page, I am utilizing an AJAX calendar to allow users to select a date. I want to restrict users from selecting past dates, current date, or dates more than 20 days in the future.

var today = new Date();
            var twentyDays = new Date();
            twentyDays.setDate(today.getDate() + 20);

            if (selectedDate.getDateOnly() <= todayDate.getDateOnly())
            {
                alert('Please choose a date in the future.');
                sender._textbox.set_Value(null);
            }
            else if (selectedDate.getDateOnly() > twentyDays.getDateOnly())
            {
                alert('Selected date should not exceed 20 days into the future');
                sender._textbox.set_Value(null);
                return;
            }

However, it seems that the code is not properly comparing the selected date against the restrictions mentioned above.

<asp:TextBox ID="txtDate" runat="server" ></asp:TextBox>
<asp:ImageButton ID="imgCalender" runat="server" ImageUrl="~/Images/Calendar.png" ToolTip="Select a Date" />
 <asp:CalendarExtender ID="calShow"  runat="server" PopupButtonID="imgCalender" PopupPosition="BottomLeft" TargetControlID="txtDate" OnClientDateSelectionChanged="CheckForPastDate"></asp:CalendarExtender>

Answer №1

Instead of using the unknown method getDateOnly(), consider using the standard getTime() method in JavaScript Date object.

Answer №2

To effectively handle this issue, it is recommended to utilize server-side logic instead of relying solely on JavaScript. The calculation today.getDate() + 20 may not yield accurate results when the resulting date falls outside the current year, such as on December 30th.

One approach is to leverage the .NET Framework's DateTime object for adding days and conducting comparisons using ASP.NET AJAX Page Methods. Here is an example:

Code-behind:

[WebMethod]
public static string CompareDate(string theDateToCompare)
{
    DateTime dateValue;

    if (DateTime.TryParse(theDateToCompare, out dateValue))
    { 
        DateTime today = DateTime.Now;
        DateTime twentyDaysFromNow = today.AddDays(20);

        if(dateValue <= today)
        {
            return "Date cannot be in the past or present"; 
        }
        else if (dateValue > twentyDaysFromNow)
        {
            return "Date should not exceed 20 days from now";
        }
    }
    else
    {
        return "Failed to parse date: " + theDateToCompare; 
    }
}

Markup:

$(document).ready(function() {
    // Implement selector event here to trigger server-side call
    $.ajax({
        type: "POST",
        url: "YourPageName.aspx/CompareDate",
        data: "{'CompareDate':'11/30/2013'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            if (result.hasOwnProperty("d")) {
                alert(result.d);
            }
            else {
                alert(result);
            }
       }
    });
});

Note: Ensure to substitute YourPageName.aspx with your actual .aspx page name. Additionally, the presence of .d in the result structure serves as a security enhancement introduced by Microsoft in ASP.NET 3.5 AJAX release to prevent XSS attacks.

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

Is it possible to deactivate link buttons when the table field equals x?

On the cart-view page, there are product panels that allow users to click an edit link button for each product. However, business rules dictate that once the cart is bound and the status field in the submission table changes from "new" to "bound", users sh ...

Ensuring Jquery validation is triggered before submitting a form to PHP

I have been struggling with a particular issue and decided to seek help. I have a form filled with user data that I have successfully validated using js/jQuery before sending it to php for processing. Here is how I am achieving this: form.submit(functio ...

What is the best method for extracting information from quills and transmitting it to the server?

Currently, I have incorporated the Quill text editor into my project. If you are interested in learning more about Quill Editor, you can check it out here. My main objective is to obtain the data from the editor and send it to the server using an AJAX cal ...

Tips for displaying the html content saved in the database onto an ejs webpage

This task seems simple, but I'm struggling to solve it. In my Node.js/Express webapp, I have the Quill.js editor installed. It stores my description in MySQL DB like this: <p><strong>This is the quill data. How are we doing dev?</stron ...

What is the best way to ensure that my image gallery adjusts its width to be responsive to the div

I am facing an issue with my image gallery named slider1_container. The style properties are defined in the HTML code as follows: <div id="slider1_container" style="position: relative; top: 0px; left: 0px; width:700px; height: 600px; background: #1 ...

Issue with applying custom theme to Tippy.js

I am trying to customize the style of a tooltip using tippy.js, following the instructions provided in the documentation: To create a custom theme, add a class to the tippy-tooltip element in the format .tippy-tooltip.x-theme. For example, let's creat ...

How to Use an Object Created from a Different Class in TypeScript

Scenario In the development process, I am using an auth.service.ts. This service is responsible for fetching user information from the database upon login. The retrieved data is then used to create a new user object. Here is a snippet of the code: user: ...

Issue with selenium webdriver isDisplayed() method in Javascript

I am currently developing a test using Selenium and JavaScript. During one part of the test, I need to go through an array of input elements and fill in values for those that are visible. if (textInputs.length > 0) { console.log('handling tex ...

Filter WordPress posts using Ajax on a specific page

I have successfully implemented a posts filter and pagination feature on my website. However, I am facing an issue with the filter when it comes to filtering posts only on the current page. Currently, if I filter posts on page 1, the filter considers p ...

NodeJS web scraping on a site that uses JavaScript

Currently, I am utilizing the request method to extract data from a particular SoundCloud page. Upon loading, SoundCloud verifies if JavaScript is enabled before displaying the track list. However, during my scraping process, I am only receiving a basic H ...

Is it possible to integrate payment methods such as PayPal or Stripe in Vue.js without using a server like Express? If so, how can I implement this

After completing the development of my web shop in Vue.js, I realized that the payment method is still missing. I am wondering if I need to integrate Express in order to process payments through Stripe? Currently, I do not have a server like Express set up ...

Execute javascript on webpage after reloading

My goal is to dynamically refresh a website and run a JavaScript script on it, simulating the behavior of executing code in the Chrome console. How can this be accomplished? One method I am considering involves using PHP to set up a local server that red ...

Transferring checkbox data to Bootstrap modals and dynamically summoning specific div modals using their unique identifiers

I have been trying to populate the checkbox values into corresponding modal divs based on button clicks, but I am facing difficulties in achieving it. Desired outcome: The buttons should trigger the display of selected checkbox values in their respective ...

How can one effectively eliminate redundant duplicates from an object in Javascript?

Review the JavaScript object provided below (note that only a portion of the object is shown). https://i.sstatic.net/5H0gn.png Here is the requirement: For each distinct user, limit the number of random leads to a maximum of 4 and discard the rest. For ...

Selecting an option containing text using Selenium and Xpath

During one of my tests, I am attempting to choose an option that includes the word "Current." The dropdown menu appears as follows: <select name="lead" class="wide"> <option value="">-- Select a lead --</option ...

Sending a response with Express before an asynchronous function has completed

app.get('/test',(req,res)=>{ doSomething().then(res.sendFile(path,(err)=>{ if (err) { console.log('err') } else { console.log('Sent:', fileName) } })) asyn ...

After installing the latest version of [email protected], I encountered an error stating "Module 'webpack/lib/node/NodeTemplatePlugin' cannot be found."

Upon updating to nextjs version 10.1.3, I encountered an error when running yarn dev. Error - ./public/static/style.scss Error: Cannot find module 'webpack/lib/node/NodeTemplatePlugin' Require stack: - /path_to/node_modules/mini-css-extract-plugi ...

Styling elements with values from an object array

I have been working on a code snippet to extract checked checkboxes and match their names with an object array in order to retrieve certain values. You can find a sample fiddle here. Now, I am wondering how I can utilize these extracted values to dynamica ...

AngularJS: Issues with retrieving response headers following a $resource $save operation

When I run the $save function, which triggers my angularJS $resource to send a POST request to my API, everything seems to be working fine. I can successfully debug into the success callback handler and confirm that the object is created in my API. myObj. ...

The Angular framework may have trouble detecting changes made from global window functions

While working, I came across a very peculiar behavior. Here is the link to a similar issue: stackblitz In the index.html file, I triggered a click event. function createClause(event) { Office.context.document.getSelectedDataAsync( Office.Coerci ...