C# .NET - Custom validator for date compare

Asked By tejasvee on 19-May-12 01:35 AM
 

Hi ,i am having to text boxes to display date.i have used  ajaxToolkit:CalendarExtender,now i want
to compare if user enter todate  and  do  not enter from date,then i want to display message:"please enter from  date". and vice versa

suggest me jquer or any ajaxToolkit:CalendarExtender way,don not want javascript.




<
tr>

<td>

<asp:Label ID="lblFromDate" runat="server" Text="From Date"></asp:Label>

</td>

<td>

<asp:TextBox ID="txtFromDate" runat="server"></asp:TextBox>

<ajaxToolkit:CalendarExtender ID="ClEFromDate" runat="server" Format="dd/MM/yyyy"

TargetControlID="txtFromDate">

</ajaxToolkit:CalendarExtender>

<ajaxToolkit:MaskedEditExtender ID="MEE_txtFromDate" runat="server" Mask="99/99/9999"

MaskType="Date" MessageValidatorTip="true" TargetControlID="txtFromDate" />

</td>

<td>

<asp:Label ID="lblToDate" runat="server" Text="To Date"></asp:Label>

</td>

<td>

<asp:TextBox ID="txtToDate" runat="server"></asp:TextBox>

<ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" Format="dd/MM/yyyy"

TargetControlID="txtToDate">

</ajaxToolkit:CalendarExtender>

<ajaxToolkit:MaskedEditExtender ID="MaskedEditExtender1" runat="server" Mask="99/99/9999"

MaskType="Date" MessageValidatorTip="true" TargetControlID="txtToDate" />

</td>

<td>

Neha Garg replied to tejasvee on 19-May-12 02:03 AM
HI...
See the below example:

<asp:TextBox ID="txtStartDate" ReadOnly="true" runat="server"
  CssClass="textBoxWidth TPRValue" Text='<%#DataBinder.Eval(Container.DataItem, "StartDate", "{0: ddd MM dd, yyyy}")%>'>
</asp:TextBox>
<asp:ImageButton ID="imgBtnStartDate" runat="server" ImageUrl="~/Common/Images/Calendar.GIF" CausesValidation="false" ImageAlign="AbsMiddle" />
<ajax:CalendarExtender ID="StartDateCalendar" TargetControlID="txtStartDate" PopupButtonID="imgBtnStartDate" runat="server"
  Format="ddd MM dd, yyyy">
</ajax:CalendarExtender>
<asp:CompareValidator ID="startDateCompareValidator" runat="server" ControlToValidate="txtStartDate" ControlToCompare="txtEndDate" Enabled="true"
  Type="Date" Display="Dynamic" Operator="LessThanEqual"
  Text="Startdate should be <= enddate">
</asp:CompareValidator>
Neha Garg replied to tejasvee on 19-May-12 02:09 AM
You can try this Javascript also....

<script type="text/javascript">
 
function checkDate(sender,args)
{
 
var selectedDate = new Date();
selectedDate = sender._selectedDate;
 
var todayDate = new Date();
var mssge = "";
 
if(selectedDate < todayDate)
{
 
sender._selectedDate = todayDate;
 
sender._textbox.set_Value(sender._selectedDate.format(sender._format));
 
alert("Date Cannot be in the past");
}
}
</script>

Somesh Yadav replied to tejasvee on 19-May-12 02:31 AM

You will have to use a http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.aspx to do this. In your markyou, you will have something like this:

<asp:TextBox ID="txbStartDate" runat="server" />
<asp:TextBox ID="txbEndDate" runat="server" />
<asp:CustomValidator OnServerValidate="ValidateDuration"
   
ErrorMessage="Dates are too far apart" runat="server" />

And in your code behind, you define the validation handler:

protected void ValidateDuration(object sender, ServerValidateEventArgs e)
{
   
DateTime start = DateTime.Parse(txbStartDate.Text);
   
DateTime end = DateTime.Parse(txbEndDate.Text);

   
int months = (end.Month - start.Month) + 12 * (end.Year - start.Year);

    e
.IsValid = months < 12.0;
}

Note that the code above is prone to throw exceptions. You will need to add additional validators to check that the dates entered can be parsed, and the ValidateDuration method should be modified to confirm that these other validators have passed before doing its own tests.

Further, you might want to yet add another validator to test that the end date is in fact greater (or equal to) the start date. Breaking this rule should probably raise its own validation error message.

<asp:CompareValidator Operator="GreaterThanEqual" Type="Date"
   
ControlToValidate="txbEndDate" ControlToCompare="txbStartDate"
   
ErrorMessage="Let's get started first!" runat="server" />
kalpana aparnathi replied to tejasvee on 19-May-12 06:45 AM
hi,

1)Create a hidden field control in aspx page

    <asp:HiddenField ID="hdnCurDate"  runat="server" />

2)Convert the date to required format from code behind aspx.cs file
 
    hdnCurDate.Value = DateTime.Now.ToString("dd-MM-yyyy");

3)Add a Custom validator for the required date field

 <asp:CustomValidator ID="date1"  runat="server" ControlToValidate="txtBirthDate"      ClientValidationFunction="validateDate" ErrorMessage="Enter less than the current date"
      CssClass="ClsRedtext"  SetFocusOnError="true">

</asp:CustomValidator>



4)Write a javascript function code :



function ValidateDate(oSrc,args)
{
    var dob =  document.getElementById('ctl00_ContentPlaceHolder1_txtBirthDate');    
    var Stmdt =  document.getElementById('ctl00_ContentPlaceHolder1_hdnCurDate');
     
     var dateOfBirth = dob.value;
     var systemDate = stmdt.value;
     var ArrDob =   dateOfBirth.split("-");
    
     var DobMonth = ArrDob[0];     
     var DobDate   = ArrDob[1];
     var DobYear   = ArrDob[2];
   
     var ArrSysDate =   systemDate.split("-");
        
     var SysDate   = ArrSysDate[0];
     var SysMonth = ArrSysDate[1];
     var SysYear   = ArrSysDate[2];
     
     
     if(DobYear > SysYear)
     {
         args.IsValid = false;
         return;
     }
     else if((DobYear == SysYear) && (DobMonth > SysMonth))
     {
         args.IsValid = false;  
         return;
     }
     
      else if((DobYear == SysYear) && (DobMonth == SysMonth) && (DobDate > SysDate))
     {
         args.IsValid = false;  
         return;
     }
      args.IsValid = true;
   }
</script>


Regards,