Date validation in asp.net for TO and FROM dates - c#

I have select criterion for the to and from dates in asp.net as below.I want to include validation for date format and also for the comaprision. How can i include below requirements in asp.net validations on sub,it button click?
If user select either TO or FROM date he must select both means TO and FROM also.
If the TO date is less than FROM date error message should be displayed.

To check the format, use CompareValidator
<asp:CompareValidator Operator="DataTypeCheck" Type="Date" ...
To check the end date is after the start, try another CompareValidator (this should work - not tested)
<asp:CompareValidator Operator="GreaterThan"
ControlToValidate="txtEnd"
ControlToCompare="txtStart"
Type="Date"
To check your more complex requirements, use the CustomValidator
<asp:CustomValidator

Related

Getting incorrect date format when retrieving data from SQL in asp.net

I have a database which has date field and time field. I want to retrieve these two values from the DB and display them in a Label. I could do this by binding an SqlDataSource with the DB and using Eval in the label, but the problem is that I always get an extra 12:00:00 am when retrieving the date. For example if the date is 13/11/2015, when I retrieve it via asp.net I get, 13/11/2015 12:00:00 am.
I have executed a query in SQL itself and the results where correct with no 12:00:00 am. Also, when I configured the 'SqlDataSource' I clicked Test Query and the results were correct.
I couldn't figure out why I'm getting incorrect format when displaying it in a label. The label is placed inside a repeater ItemTemplate. All other retrived data from the DB are retrieved correctly from inside the repeater except date. Here is the code which places the date in the Label,
<span class="date_time_lbl">posted at: </span>
<asp:Label runat="server" Text='<%#Eval("tDate") %>'/>
<span> </span>
<asp:Label runat="server" Text='<%#Eval("Time") %>'/>
Can anyone please tell me what is causing this problem?
you can use formating in eval as a second parameter;
Eval("Date", "{0:d}")
for standard format options:
https://msdn.microsoft.com/library/az4se3k1(v=vs.100).aspx
for custom options:
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

How to show multiple calendars with one texbox in asp.net?

I need to make a textbox that will select date range. It needs to display two calendars (Start Date and End Date) when it gets clicked. I am using Ajax control toolkit but it shows only one calendar and when I add two calendars with same TargetControlID, it still shows one calender.
<asp:TextBox ID="startDate" Text="Start Date" ReadOnly="False" EnableViewState="True" CssClass="calendar" runat="server">
</asp:TextBox>
cc1:CalendarExtender EnabledOnClient="True" DefaultView="Days" PopupButtonID="calenderopener"
ID="startDate_CalendarExtender" StartDate="Jan 15, 2014" CssClass="ajax__calendar ajax__calendar_container" EnableViewState="True"
runat="server" BehaviorID="calendar1" Enabled="True" TargetControlID="startDate" Format="MM/dd/yyyy">
</cc1:CalendarExtender>
I want to show two calendars when this textbox gets clicked.
Try this. This allows you to select multiple dates to single control(Textbox). If you want to use date range (only two days are selectable) then you shoud have to validate it in your code behind.
http://www.obout.com/calendar/tutorial_select_multipledates.aspx

ASP.NET date validator passing when it should not

I'm using a RegularExpressionValidator in ASP.NET. I have these validators for my asp:Textbox control:
<asp:RangeValidator
ID="rvDate"
runat="server"
ControlToValidate="txtCrimeDate"
Type="Date"
ErrorMessage="Must be within latest three months"
Display="Dynamic"
OnInit="RangeValidator_Init">
</asp:RangeValidator>
<asp:RegularExpressionValidator
ID="revDate"
runat="server"
ControlToValidate="txtCrimeDate"
Display="Dynamic"
ErrorMessage="Must be in format YYYY-MM-DD"
ValidationExpression="[0-9]{4}-[0-9]{2}-[0-9]{2}">
</asp:RegularExpressionValidator>
I have set the min and max value of the RangeValidator in the code-behind and it works as intended. But! If I enter something with 2 numbers for the year, like 15-11-28 everything passes, even the other validators for the other controls. Any ideas?
Check the date format (US or otherwise) and 0-9 for the day and month are incorrect eg:
2013-99-99
Look into using the CompareValidator control, this is mainly used for string matching, but can be made to check between two date ranges.

How to Use a Compare Validator with DateTime.Today against TextBox.Text?

Goal:
I have an 'EndDate' TextBox that updates upon the user changing it. I want to be able to check/validate the date in EndDateTextBox.Text and make sure it is less than today's date (in format ex: 4/19/2013).
I've tried two methods:
Method One
<asp:TextBox ID="HiddenTodayDate" Visible = "false" runat="server" />
<asp:CompareValidator ID="CompareEndTodayValidator" Operator="GreaterThan" Type="Date"
ControlToValidate="HiddenTodayDate" ControlToCompare="EndDateTextBox"
ErrorMessage="'End Date' must be before today's date" runat="server" />
And the following in my Page_Load method:
HiddenTodayDate.Text = DateTime.Today.ToShortDateString();
Method Two
<asp:HiddenField ID="HiddenTodayDate" runat="server" />
<asp:CompareValidator ID="CompareEndTodayValidator" Operator="GreaterThan" Type="Date"
ControlToValidate="HiddenTodayDate" ControlToCompare="EndDateTextBox"
ErrorMessage="'End Date' must be before today's date" runat="server" />
And the following in my Page_Load method:
HiddenTodayDate.Value = DateTime.Today.ToShortDateString();
To the code savvy obviously setting a TextBox visible to false prevents the Validator from seeing it as well, but I didn't know it at the time and wanted to document my process. When I try method two, I come across the following error when debugging:
Control HiddenTodayDate referenced by the ControlToValidate property
of `CompareEndTodayValidator cannot be validated.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Control 'HiddenTodayDate'
referenced by the ControlToValidate property of
'CompareEndTodayValidator' cannot be validated.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
So is there a means to somehow achieve my goal without having to display DateTime.Today somewhere? I'd prefer to keep my code as simple and clean as possible and not use Javascript, but if Javascript provides the only workaround, then so be it. Code would be greatly appreciated. Thanks!
After learning of the the ValueToCompare property due in part to Tim's post I was able to search around and find a question similar to mine with an answer that almost worked (had to change ASP.NET compare type to String):
Using the CompareValidator control to compare user input date with today's date
Here's what my code looks like:
ASP.NET:
<asp:CompareValidator ID="CompareEndTodayValidator" Operator="LessThan" type="String" ControltoValidate="EndDateTextBox" ErrorMessage="The 'End Date' must be before today" runat="server" />
.NET:
(In Page_Load method)
CompareEndTodayValidator.ValueToCompare = DateTime.Now.ToShortDateString();
You can set the ValueToCompare property programmatically to today:
<asp:comparevalidator runat="server" Id="CompareEndTodayValidator"
errormessage="The date must be less than today"
controltovalidate="EndDate" type="Date" Operator="LessThan"
ValueToCompare="<%= DateTime.Today.ToShortDateString() %>" />
(not tested, if <%= doesn't work use <%#, then you have to remember to call Page.DataBind() somewhere(f.e. in Page_Load) if it is not in a databound context)

ASP.NET Validators - checking if the sum of two textbox's equals a certain value

Basically, I have 2 textbox's which the user enters currency/numeric values - I want to have a validator that checks if the values in these box's add up to make another value. Is there a built in validator for this or would I have to use a custom validator?
You need a custom validator for that. There exist no standard validators in ASP.NET that do the sum checking you require.
See also:
http://asp.net-tutorials.com/validation/custom-validator
http://msdn.microsoft.com/en-us/library/f5db6z8k(v=vs.71).aspx
http://www.codeproject.com/KB/validation/aspnetvalidation.aspx
Good luck!
if bothe values are required :
so 2 of
<asp:RequiredFieldValidator ID="VAL_Req_Pass" runat="server" ControlToValidate="TXT_Password"
Display="Dynamic" ValidationGroup="User">Required</asp:RequiredFieldValidator>
and one of :
<asp:CustomValidator ID="CustomValidator2" runat="server" ValidationGroup="User"
ErrorMessage="Password does not match"
ClientValidationFunction="passwordMatch"
ControlToValidate="TXT_Password"
Display="Dynamic" >
</asp:CustomValidator>
which has js function that checks if equal...

Categories