Tips for verifying a string date using the Ajax Control Toolkit (CalendarExtender) technology

I have a dilemma with two formatted TextBoxes that receive their text value from a CalendarExtender. I need to validate that the first TextBox is greater than the second one, but the values are coming in as strings rather than dates. How can I go about validating this? Here is my ASP code:

<asp:TextBox ID="TextBox1" runat="server" style="width:160px; text-align:center;" OnServerValidate="DateRange_ServerValidate"></asp:TextBox> 

<asp:TextBox ID="TextBox2" runat="server" style="width:160px; text-align:center;" OnServerValidate="DateRange_ServerValidate"></asp:TextBox> 

<asp:Label ID="lblDateError" runat="server"  ForeColor="#CC0000" ></asp:Label>

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
            </asp:ToolkitScriptManager>

            <asp:CalendarExtender ID="CalendarExtender1" runat="server"  Format="dddd, MMMM dd yyyy"
                TargetControlID="TextBox1" PopupButtonID="Image1">                    
            </asp:CalendarExtender> 

            <asp:CalendarExtender ID="CalendarExtender2" runat="server" Format="dddd, MMMM dd yyyy"
                TargetControlID="TextBox2" PopupButtonID="Image4">                    
            </asp:CalendarExtender>

Regarding the code behind:

    protected void DateRange_ServerValidate(object sender, EventArgs args)  
{


    DateTime ToDate = DateTime.ParseExact(TextBox1.Text.ToString(), "dddd, MMMM dd yyyy", CultureInfo.InvariantCulture);
    DateTime currentdate = DateTime.ParseExact(TextBox2.Text.ToString(), "dddd, MMMM dd yyyy", CultureInfo.InvariantCulture);


    if (ToDate < currentdate)
    {
        lblDateError.Visible = true;
        lblDateError.Text = "End Date should not be earlier than the current date.";
        return;
    }
    else
    {
        lblDateError.Text = "";
    }

}

Any assistance would be greatly appreciated!

Answer №1

If you want to compare dates in ASP.NET, you can simply use the comparevalidator by setting the "Type" attribute to "Date".

Here is an example:

<asp:TextBox ID="Textbox1" runat="server"></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="CalendarExtender2" runat="server" TargetControlID="Textbox1"></ajaxToolkit:CalendarExtender>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="TextBox2"></ajaxToolkit:CalendarExtender>
<asp:CompareValidator ID="CompareValidator1" ControlToCompare="Textbox1"  Operator="LessThan" 
    ControlToValidate="TextBox2" Type="Date"  runat="server" ErrorMessage="Invalid Date Range"></asp:CompareValidator>
<asp:Button runat="server" Text="validate"/>

If you need to validate this on the server side, you can simply call the following:

CompareValidator1.Validate();

Answer №2

DateTime startDate;
DateTime endDate;
if (DateTime.TryParse(StartTextBox.Text, out startDate) && DateTime.TryParse(EndTextBox.Text, out endDate) && startDate <= endDate)
throw new Exception("This is not acceptable.");

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

Streamline the entire testing process of Google.Com by using Protractor to automate end-to-end testing

I need help with making Protractor navigate to google.com and search for a term. After successfully loading the non-angular page of Google, I am struggling to figure out how to make Protractor press "enter" or click the search button. Any suggestions? Ad ...

What is the best way to retrieve the values from the labels for two separate buttons?

I designed a pair of buttons with a single label below. Both buttons acted as standalone entities. <label for="buttons" class ="val">0</label> <input class="btn btn-primary button1" type="button" ...

Securing the owning object with a lock

After reviewing numerous examples, I've observed a common pattern in which locks on instances are utilized in the following manner: public class Foo { readonly object locker = new Object(); public void DoSomething() { lock(locker) { ...

Verify the presence of the promotion code and redirect accordingly

I have created a special promotion page that I want to restrict access to only users who have received a unique code from me via email. To achieve this, I have designed the following form: <form accept-charset="UTF-8" action="promotion.php" method="po ...

Dynamic population of dropdown not working as expected

Below is the code I am using to populate a Dropdown: $(document).ready(function(){ $('#inDistrict').sSelect(); $("#inDistrict").change(function(){ $.getJSON("filldistricts.php",{id: $(this).val(), ajax: 'true'}, function(j) ...

Mastering file handling with jQuery File Upload Middleware in Node.js Express: blending files and branding with watermarks

I was successful in setting up the jquery-file-upload-middleware with express.js 4.0, but I am struggling with configuring it properly. Here is the script I used for upload: var upload = require('jquery-file-upload-middleware'); upload.configur ...

What is the method to hide a link button on a grid view upon clicking it?

I am working on a grid view that contains link buttons. I want to perform a specific operation when clicking on one of the link buttons, and at the same time, make that particular button invisible. How can I achieve this? Here is a snippet of my code: & ...

Updating field based on dropdown value in CakePHP 3.6.11

I have the following tables: customers[id, name, surname, phone, text, balance, created] service_types[id, title, price, length, is_subscription, created] customer_service_types[id, customer_id, service_type_id, price, created] Within the add.ctp file o ...

An issue has occurred with System.Net.HttpWebRequest.GetResponse() stating "Prior to calling [Begin]GetResponse, you are required to write ContentLength bytes to the request stream."

I am encountering an error called "System.Net.ProtocolViolationException" when trying to upload a large file using a method to our server. Despite increasing the size limit in the web.config file, the error persists. <httpRuntime maxRequestLength="3548 ...

Retrieving information from mlab without needing to make a new request, for example, updating the front end without refreshing the page

I understand that many people have asked questions similar to mine, but my issue is unique. I am trying to retrieve data from my mlab database without having to reload the page. For example, when a new cricket score is added to my db in mlab, I want this s ...

Data retrieval takes precedence over data insertion

I'm facing an issue where I am trying to insert data into MySQL using Knex within a loop, but the data retrieval is happening before the insertion. Can anyone assist me with this problem? for (let i = 0; i < fileArray.length; i++) { fileLocation ...

"Seeking assistance with implementing a Toggle Button using AJAX in an ASP.NET environment

My goal is to dynamically update the page each time the checkbox is checked or unchecked using a Toggle Button from AJAX. However, I have been facing difficulties in achieving this functionality. Although it works perfectly with a button and an image butto ...

The SQL server is experiencing difficulty in showcasing records over LAN via asp.net

Running an ASP.NET application on an intranet, utilizing SQL Server 2008 to display records with the main server acting as the system. The firewall is turned off on all systems. However, when a friend tries to access the ASP.NET site via the IP address on ...

Express routes are malfunctioning

I have a situation with two different routes: /emails and /eamils/:id: function createRouter() { let router = express.Router(); router.route('/emails/:id').get((req, res) => { console.log('Route for get /emails/id'); }); ...

Concurrently invoking a C# async method should ensure that it waits for the completion of the initial operation

My current method looks like this: public async Task<OpenResult> openAsync() I am looking for a way to queue up any subsequent calls to openAsync while a current call is being executed. Once the initial call is completed, I would like to process al ...

Exploring Google with Angular.js

When designing my website, I incorporated Angular in a specific section rather than the entire site. However, I have learned that Google encounters difficulties when indexing Angular content. To ensure optimum visibility for both search engines and users ...

Utilizing Typeahead for Autocomplete in Durandal: A Step-by-Step Guide

I am attempting to implement an autocomplete input field with typeahead (Twitter Bootstrap) in a modal, but I am encountering difficulties making it function properly. Additionally, this autocomplete field needs to be observable with Knockout so that selec ...

utilizing numerous conditional renderings within a mapping function

Hello there, I'm curious if there is a more efficient method to display my todos. Currently, my code looks like this: { todos.map((todo) => ( todo.status === 1 && ( ...

Change the size of a particular div upon hovering over another element

I'm trying to figure out how to scale my div with text when a user hovers over a button, but I've tried various operators like >, ~, +, - with no success. section { background: #000; color:#fff; height: 1000px; padding: 150px 0; font-family ...

Sending a CSS class name to a component using Next.js

I am currently in the process of transitioning from a plain ReactJS project to NextJS and I have a question. One aspect that is confusing me is how to effectively utilize CSS within NextJS. The issue I am facing involves a Button component that receives ...