Asp.net compare validator to validate date

人盡茶涼 提交于 2019-11-30 18:40:17
Ebad Masood

Try this approach, First Enter the Start Date and Check the Compare Validator with the End Date textbox:

<asp:CompareValidator id="cvtxtStartDate" runat="server" 
     ControlToCompare="txtStartDate" cultureinvariantvalues="true" 
     display="Dynamic" enableclientscript="true"  
     ControlToValidate="txtFinishDate" 
     ErrorMessage="Start date must be earlier than finish date"
     type="Date" setfocusonerror="true" Operator="GreaterThanEqual" 
     text="Start date must be earlier than finish date"></asp:CompareValidator>

Compare validator has the type=date.But that date type is constrained to accept only particular format of date i.e ToShortDateString(). If the date format of the two textboxes to be compared is in some other format like ToLongDateString() or some format specified by ToString("dd MMMM,yyyy") the comparision does not work. CustomValidator isonly option. If you want to use compare validator only then

textstartdate.text=Calendar1.SelectedDate.ToShortDateString();
textfinishdate=Calendar2.SelectedDate.ToShortDateString();
<asp:CompareValidator ID="CompareValidator4" runat="server" 
                    ControlToCompare="textstartdate" ControlToValidate="textfinishdate" 
                    CultureInvariantValues="True" 
                    ErrorMessage="Date should be greater than booking date." 
                    Operator="GreaterThanEqual" SetFocusOnError="True" Type="Date"></asp:CompareValidator>

Try custom Validator and at the code behind at onservervalidate event convert the text to DateTime and then do the comparision.

protected void DateTimeComparision_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = Convert.ToDateTime(txtStartDate.Text) < Convert.ToDateTime(txtFinishDate.Text);
    }
function FromAndToDateValidate() {
try {
    var StartDate = new Date();
    StartDate = $("#dtpFromDate").val();

    var EndDate = new Date();
    EndDate = $("#dtpToDate").val();
    args.IsValid = (StartDate <= EndDate);
}
catch (ex) {
    alert(ex);
}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!