Compare DateTime using CompareValidator in ASP.Net

Last Reply 2 months ago By dharmendr

Posted 2 months ago

how to compare date and time both with current date and time using compare validator? 

The format should be (mm/dd/yyyy HH:mm) for comparision.

 

Posted 2 months ago

I am checking it, I will get back to you soon.


Posted 2 months ago

Hi rajiv7577,

Please refer below sample.

HTML

<div>
    Date:
    <asp:TextBox ID="txtDateTime" runat="server"></asp:TextBox>
    <asp:CompareValidator ID="cvDateTime" runat="server" Operator="Equal" ControlToValidate="txtDateTime"
        ErrorMessage="Not valid" Type="Date"></asp:CompareValidator>
</div>

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    cvDateTime.ValueToCompare = DateTime.Now.ToShortDateString();
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    cvDateTime.ValueToCompare = DateTime.Now.ToString("MM/dd/yyyy")
End Sub

Screenshot


Posted 2 months ago

thanks for replying.But I want to compare both date and time with current date and time.The format should be (mm/dd/yyyy HH:mm) for comparision.


Posted 2 months ago

Hi rajiv7577,

You are trying to compare DateTime. The CompareValidator do not support DateTime. The Date Type is only for dates, not times.

You cannot use the CompareValidator.

You have to write a CustomValidator that can interpret the values of the dates.

Refer below link.

Start Time and End Time validation using CustomValidator in ASP.Net