Check date is Greater using Calendar control in Asp.Net - asp.net

I'm having a situation where i'm having a Calendar control in my page and when user selects a date it should check whether date selected is greater than today's date.
I tried a lot and Googled it as well, but in every place they are taking value using a textbox and i want the same to be done with a Calendar control.

Contrary to popular belief, you actually don't need any C# code to get this done! All you need is some extenders and validators on your date textbox. So let's say I had two textboxes -- one named txtStartDt and one named txtEndDate; this is how the extensions for them would be placed:
// Start Date
<asp:TextBox ID="txtStartDt" runat="server" CssClass="textboxint" /> // the main control itself
<ajax:CalendarExtender ID="calStartDt" runat="server" PopupPosition="BottomRight"
TargetControlID="txtStartDt" /> // allows the control to behave like a calendar picker
<asp:CompareValidator ID="CVStartDt" runat="server" Type="Date" Operator="LessThan"
ErrorMessage="Start Date must come before the End Date" ValidationGroup="ReportDate"
ControlToValidate="txtStartDt" ControlToCompare="txtEndDt" Display="None" /> // THIS is the main solution to your problem
<ajax:ValidatorCalloutExtender ID="VCEStartDt" runat="server" TargetControlID="CVStartDt"
HighlightCssClass="valCalloutint" /> // Checks that the CV is working correctly
<asp:RequiredFieldValidator ID="RFVStartDt" runat="server" ControlToValidate="txtStartDt"
Display="None" ErrorMessage="Start Date is required" ValidationGroup="ReportDate" /> // ensures a value was added to the textbox
<ajax:ValidatorCalloutExtender ID="VCEreqStartDt" runat="server" TargetControlID="RFVStartDt"
HighlightCssClass="valCalloutint" PopupPosition="BottomRight" /> // Checks that the RFV is working correctly
// End Date
<asp:TextBox ID="txtEndDt" runat="server" CssClass="textboxint" />
<ajax:CalendarExtender ID="calEndDt" runat="server" PopupPosition="BottomRight" TargetControlID="txtEndDt" />
<asp:CompareValidator ID="CVEndDt" runat="server" Type="Date" Operator="GreaterThan"
ErrorMessage="End Date must come after the Start Date" ValidationGroup="ReportDate"
ControlToValidate="txtEndDt" ControlToCompare="txtStartDt" Display="None" />
<ajax:ValidatorCalloutExtender ID="VCEEndDt" runat="server" TargetControlID="CVEndDt"
HighlightCssClass="valCalloutint" />
<asp:RequiredFieldValidator ID="RFVEndDt" runat="server" ControlToValidate="txtEndDt"
Display="None" ErrorMessage="End Date is required" ValidationGroup="ReportDate" />
<ajax:ValidatorCalloutExtender ID="VCEreqEndDt" runat="server" TargetControlID="RFVEndDt"
HighlightCssClass="valCalloutint" PopupPosition="BottomRight" />
Note that the extra ValidatorCalloutExtender tools are not redundant, but actually allows the program to prevent the user from entering an empty value for one of the textboxes.
Hope this helps!!

The calendar control should have a property called SelectedDate. You can compare this property with any other DateTime property. The code snippet below will check if the SelectedDate is greater than today.
if (Calendar.SelectedDate > DateTime.Now())
{
}

Related

ASP.NET Validator Issue when setting Display =“Dynamic”

We recently upgraded our application from .Net 2/vs 2005 to .net 4.5/vs2012 and are seeing exactly same issue noted in ASP.NET Validator Issue when setting Display ="Dynamic" this question. My submit button moves down on validation failure and we have to double click to trigger postback. Adding <br /> before submit button is not acceptable solution for us as we have over 200 pages. Is there any generic solution to this problem.
below is the code snippet:
<asp:textbox id="txtCancellationDays" runat="server" maxlength="3"/>
<asp:rangevalidator id="rvCancelDays" runat="server" controltovalidate="txtCancellationDays"
maximumvalue="999" minimumvalue="0" type="Integer" text="Cancellation cutoff days must be a number between 0 and 999." />
<asp:requiredfieldvalidator id="rfvCancelDays" runat="server" display="Dynamic" controltovalidate="txtCancellationDays"
text="Cancellation Cutoff Days is required" />
<asp:comparevalidator id="cvCancelDays" text="Cancel Days must be less than or equal to Waitlist Days"
runat="server" controltovalidate="txtCancellationDays" controltocompare="txtWaitlistDays" type="Integer"
operator="LessThanEqual" />

Validation Summary not picking up Error Message in group

I have several required fields and regex's on my form. The validation is fired on a button click. When the button is clicked, the error messages are showing where the asp:RequiredField are declared and not in the validation summary. Here is my code:
Validation Summary:
<asp:ValidationSummary id="mySummary" DisplayMode="List" HeaderText="Error:" EnableClientScript="true" ShowSummary="true" runat="server" ValidationGroup="valGroup" />
Required Fields/Regex:
<!-- Required -->
<asp:RequiredFieldValidator ID="reqField1" ControlToValidate="txtSomething" ErrorMessage="Something is required" runat="server" Display="Static" InitialValue="" ValidationGroup="valGroup" />
<!-- Regex -->
<asp:RegularExpressionValidator runat="server" id="regexField1" ControlToValidate="txtSomething"
ErrorMessage="Something in the wrong format." ValidationExpression="^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$" ValidationGroup="valGroup">
</asp:RegularExpressionValidator>
Button:
<asp:LinkButton ID="btnValidate" runat="server" CausesValidation="True" ValidationGroup="valGroup" >Validate</asp:LinkButton>
Any suggestions?
It's hard to tell from this, as it does look like it's setup correctly to me. The only way to debug is to check the Page.Validators collection, find the validators in there, and ensure IsValid is false for those guys. All the ValidationSummary does is check this collection, and for any with a matching validation group, if the IsValid property is false, adds it to the list that's rendered out.

Regular expression for date in asp.net?

In web application, i am using regular expression for date like "dd-mm-yyyy" format for this i get the validation but it is not working when we enter date like "12-02-2012" remaining condition it is working fine, can you help me this is my validation expression.
<asp:RegularExpressionValidator ID ="myg" runat ="server" ControlToValidate ="txt" ErrorMessage ="Check"
ValidationExpression ="^(((0[1-9]|[12]\d|3[01])-(0[13578]|1[02])-((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)-(0[13456789]|1[012])-((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$" >
</asp:RegularExpressionValidator>
I solve the problem,
ValidationExpression ="^(((0[1-9]|[12]\d|3[01])-(0[13578]|1[02])-((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)-(0[123456789]|1[012])-((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$"
asp:RegularExpression is not the way to do this.
For validating date using an ASP.NET Validator its ideal to use asp:CompareValidator
Here is a small mock-up
<asp:TextBox ID="txtDatecompleted" runat="server"/>
<asp:CompareValidator ID="dateValidator" runat="server"
ControlToValidate="txtDatecompleted"
ErrorMessage="Please enter a valid date."
Operator="DataTypeCheck"
Type="Date"
ValidationGroup="TestVGroup">
</asp:CompareValidator>
<br />
<asp:Button ID="ClickButton" Text="Click Me" runat="server"
ValidationGroup="TestVGroup"
OnClick="ClickButton_Click" />
This will automatically check for different date formats and leap years
I slove the problem,
ValidationExpression ="^(((0[1-9]|[12]\d|3[01])-(0[13578]|1[02])-((19|[2-9]\d)\d{2}))|
((0[1-9]|[12]\d|30)-(0[123456789]|1[012])-((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])
\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|
((16|[2468][048]|[3579][26])00))))$"

AutoPostBack on CheckBox control sometimes fails

If have the below markup.
<asp:checkbox id="chkTVLic" runat="server" text="TV Licence" oncheckedchanged="chkDocs_CheckChanged"
autopostback="true" CausesValidation="false" />
<asp:panel id="pnlTVLic" runat="server" visible="false">
<div class="toggle-item-link1 document-date">
<asp:panel id="pnlTVLicIssueDate" runat="server">
<p>
Please enter the date of issue
</p>
<div class="fm-req">
<asp:textbox id="txtTVLicIssueDate" cssclass="tb size2" runat="server" onblur="return true;"></asp:textbox>
<cc2:calendarextender id="caleTVLicIssueDate" runat="server" targetcontrolid="txtTVLicIssueDate"
popupbuttonid="ibnTVLicIssueDate" popupposition="BottomLeft" animated="true"
format="dd/MM/yyyy">
</cc2:calendarextender>
<asp:imagebutton id="ibnTVLicIssueDate" runat="server" imageurl="../images/img-calendar-day.png"
alternatetext="Calendar" tooltip="Pick Date" cssclass="date-picker" />
<asp:requiredfieldvalidator id="rfvTVLicIssueDate" CssClass="error" runat="server" controltovalidate="txtTVLicIssueDate"
display="Dynamic" errormessage="Required" setfocusonerror="true" validationgroup="TVLic"></asp:requiredfieldvalidator>
<asp:comparevalidator id="cmvTVLicIssueDate" CssClass="error" runat="server" errormessage="Not a valid date"
controltovalidate="txtTVLicIssueDate" operator="DataTypeCheck" type="Date" setfocusonerror="true"
validationgroup="TVLic" display="Dynamic" cultureinvariantvalues="true"></asp:comparevalidator>
<asp:customvalidator id="cuvTVLicIssueDate12Months" CssClass="error" runat="server" controltovalidate="txtTVLicIssueDate"
validationgroup="TVLic" display="Dynamic" onservervalidate="cuvDocIssueDate12Months_ServerValidate"
errormessage="Document must be less than 12 months old."></asp:customvalidator>
</div>
</asp:panel>
<asp:panel id="pnlTVLicApprove" runat="server">
<asp:LinkButton id="lbnTVLicApprove" runat="server" CssClass="screen-hide"
alternatetext="Confirm TV Licence" tooltip="Confirm TV Licence" Text="OK" CausesValidation="false" OnClick="lbnApproveConfirm_Click" />
<asp:imagebutton id="ibnTVLicApprove" runat="server" imageurl="../images/img-accept-doc-off.png"
alternatetext="Approve" tooltip="Approve" cssclass="approval-btn" causesvalidation="true" validationgroup="TVLic" OnMouseDown="HandleApproveClick('TVLic','lbnTVLicApprove');return false;" OnClientClick="HandleApproveClick('TVLic','lbnTVLicApprove');return false;" />
<span class="approval-label">Accept document:</span></asp:panel>
</div>
</asp:panel>
The app is written in c# but i havn't posted any actual code as all the user code related to this markup seems to work fine.
The problem is the CheckBox chkTVLic has causes validation set to false and autopostback set to true. So whatever happens when i check and uncheck the checkbox it should postback. Most of the time this is exactly what it does and the result is to show and hide pnlTVLic when it is checked and unchecked. However if any on the validators within the panel fire, the checkbox does not cause a postback the first time. It will on all subsequent times but never the first. However it should ALWAYS cause a postback. What could be stopping it. Before someone asks there is no use written client side code, everything is pure .net markup and c# code.
I don't see why it shouldn't postback when you check/uncheck the checkbox, but if the only purpose of that checkbox is to hide/unhide a panel, I would rather do it in javascript. Doing a full postback to the server just for hiding some panel seems really bad.
In javascript you can do this to hide the panel:
document.getElementById('<%=pnlTVLic.ClientID%>').display='none';
And this to show it:
document.getElementById('<%=pnlTVLic.ClientID%>').display='block';
It's going to be so much faster and better. Just put a regular checkbox instead of the ASP.NET one and subscribe to the onclick event.
Sorry, one more comment:
I think you are wrong when you say that the checkbox should ALWAYS cause a postback. No, if one of the validators fires inside the panel, the checkbox will not cause a postback until the condition is satisfied.
This is what I did and it worked.
on checkbox onclick event I disabled all the validation controls and immediately did Page_ClientValidate(); and it worked.

validate a textbox value for the current date in asp.net

i have a calendar control whose value will be displayed in a textbox, i need to validate the textbox value to the current date... It should not be less than current date.....
Thanks for ur valuable reply for my last post
You can use the CompareValidator control, like this:
<asp:CompareValidator ID="dateValidator"
ControlToValidate="IdOfTextBox"
Text="error message"
Operator="GreaterThanEqual"
Type="Date"
runat="server" />
And in the code-behind, set the ValueToCompare property of the validator to DateTime.Today (for example in the Page_Init method).
Try This in Code Behind :
<asp:CompareValidator ID="CompareValidator2" runat="server" ErrorMessage="Date Should be Greater Than Current Date"
ControlToValidate="txt_DateFrom" ValuetoCompare='<%# DateTime.Now.ToString("d") %>' SetFocusOnError="true" Display="Dynamic" />
Use CompareValidator control, set properties as below:
operator = GreaterThanEqual
Type = Date
ValueToCompare = CurrentDate

Resources