Validation for date with CompareValidator - asp.net

I'm using a textbox with a calendar extender to input a date of birth. I'm validating the date to be today or older. I have the following code:
<asp:TextBox ID="txtDateOfBirth" runat="server" </asp:TextBox><ajaxToolkit:CalendarExtender ID="txtDateOfBirth_CalendarExtender" runat="server" Enabled="True" TargetControlID="txtDateOfBirth" Format="MM/dd/yyyy" </ajaxToolkit:CalendarExtender>
<asp:CompareValidator ID="cvDateOfBirth" runat="server" ControlToValidate="txtDateOfBirth" ErrorMessage="Must be today or older" Display="Dynamic" Operator="LessThanEqual"></asp:CompareValidator>
I have the following in my Page_Load
cvDateOfBirth.ValueToCompare = DateTime.Today.ToString("MM/dd/yyyy");
In the CompareValidator I have the Type set to string. If I set it to Date I get an error
The value '04/21/2013' of the ValueToCompare property of 'cvDateOfBirth' cannot be converted to type 'Date'.
I'm formatting the date as MM/dd/yyyy because if I don't format the date to have the MM first (and leave it default), it is inserted with the Day and Month reversed or out of range exception if the month is larger than 12 (SQL 2008 R2). If I leave the Type as String, the validation works correctly but only for this year. If I select a date like 12/31/2012 (Dec 31, 2012) the validation fails. Can anyone point out what I'm doing wrong. Also, I read some posts where they say the Type must be set to Date for the CompareValidator, but I get an error which I mentioned above. Also why would this be set to Date and not String when I'm comparing it to a string from the textbox. Thanks for help.

First you have to do (assign compare date with today date):
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
cvDateOfBirth.ValueToCompare = DateTime.Today.Date.ToString("dd/MM/yyyy");
}
}
then 2 way to get results, that you want ::
First Way :
<asp:TextBox ID="txtDateOfBirth" runat="server"></asp:TextBox><ajaxtoolkit:CalendarExtender
ID="txtDateOfBirth_CalendarExtender" runat="server" Enabled="True" TargetControlID="txtDateOfBirth"
Format="dd/MM/yyyy">
</ajaxtoolkit:CalendarExtender>
<asp:CompareValidator ID="cvDateOfBirth" runat="server" ControlToValidate="txtDateOfBirth" SetFocusOnError="true"
Type="Date" Operator="LessThanEqual" ErrorMessage="Incorrect Date"
ForeColor="Red"></asp:CompareValidator>
then in code behind .cs file get selected date in MM-dd-yyy to save in database as::
protected void OnSave_Click(object sender, EventArgs e)
{
DateTime selcetdDate=Convert.ToDateTime(txtDateOfBirth.Text);
string date = selcetdDate.ToString("MM/dd/yyyy");
}
Other way to achieve it:
<script type="text/javascript">
function getDOB() {
var selected = document.getElementById('lbl_date').value;
var txtDateOfBirth = document.getElementById('txtDateOfBirth');
if (selected != "") {
var st = selected.split('/');
txtDateOfBirth.value = st[1] + '/' + st[0] + '/' + st[2];
}
else
txtDateOfBirth.value = "";
}
</script>
<asp:TextBox ID="txtDateOfBirth" runat="server"></asp:TextBox>
<asp:TextBox ID="lbl_date" runat="server" Text="" style="display:none;" onchange="getDOB()"></asp:TextBox>
<ajaxtoolkit:CalendarExtender
ID="txtDateOfBirth_CalendarExtender" runat="server" Enabled="True" TargetControlID="lbl_date" PopupButtonID="txtDateOfBirth"
Format="dd/MM/yyyy">
</ajaxtoolkit:CalendarExtender>
<asp:CompareValidator ID="cvDateOfBirth" runat="server" ControlToValidate="lbl_date" SetFocusOnError="true"
Type="Date" Operator="LessThanEqual" ErrorMessage="Incorrect Date"
ForeColor="Red"></asp:CompareValidator>
</div>
In codebehind .cs file
protected void OnSave_Click(object sender, EventArgs e)
{
string date = txtDateOfBirth.Text;
}
The CompareValidator property ValueToCompare for date having default format dd-MM-yyyy so we have to manually do this for comparing with other date formats. So you can use the above two options to get compare validation with date format MM/dd/yyyy.
Cheers !

Related

CustomValidator doesnt display a message unless I use a validation summary

I want to output a message in case if an invalid date was supplied.
<asp:TextBox ID="RegistrationFromTextBox2" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="RegistrationFromTextBox2" OnServerValidate="CustomValidator1_ServerValidate" ValidationGroup="NewMailingItem" runat="server" ErrorMessage="The date is invalid"></asp:CustomValidator>
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
try
{
DateTime temp;
if (DateTime.TryParse(args.Value, out temp))
{
args.IsValid =true;
}
else
{
args.IsValid = false;
}
}
catch (Exception ex)
{
args.IsValid = false;
}
}
I expect the output message to be located near the field.
Instead I get no response, even though the function works. I only get the error message if I put a validation summary to my form.
Is there away display the message without the validation summary?
Is there away display the message without the validation summary?
You will need to use Text attribute instead of ErrorMessage.
<asp:CustomValidator ID="CustomValidator1"
ControlToValidate="RegistrationFromTextBox2"
OnServerValidate="CustomValidator1_ServerValidate"
ValidationGroup="NewMailingItem"
runat="server"
Text="The date is invalid">
</asp:CustomValidator>
FYI: If you just want to validate date, you could use CompareValidator or Ajax Control Toolkit's Calendar control.
<asp:TextBox ID="RegistrationFromTextBox2" runat="server"
placeholder="MM/DD/YYYY">
</asp:TextBox>
<asp:CompareValidator
ID="RegistrationFromCompareValidator" runat="server"
Type="Date"
Operator="DataTypeCheck"
ControlToValidate="RegistrationFromTextBox2"
Text="The date is invalid">
</asp:CompareValidator>

check RadDateTimePicker value against current system date time value

How can I verify if the selected datetime value from the RadDateTimePicker is greater then the current system datetime value in asp.net using server side validaton.
<telerik:RadDateTimePicker runat="server" ID="orderDate" >
<Calendar ID="Calendar1" runat="server" EnableKeyboardNavigation="true">
</Calendar>
</telerik:RadDateTimePicker>
To validate it, you need to use CompareValidator or CustomValidator.
Please use following markup for datetime picker:
<telerik:RadDateTimePicker runat="server" ID="orderDate">
<Calendar ID="Calendar1" runat="server" EnableKeyboardNavigation="true">
</Calendar>
</telerik:RadDateTimePicker>
<asp:CustomValidator ID="cvOrderDate" runat="server" ControlToValidate="orderDate" ValidationGroup="vgSubmit" ErrorMessage="Please use correct date" OnServerValidate="cvOrderDate_ServerValidate"></asp:CustomValidator>
Code behind:
protected void cvOrderDate_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = orderDate.SelectedDate.Value > DateTime.Now;
}
There is also a demo of RadDateTimePicker validation here http://demos.telerik.com/aspnet-ajax/calendar/examples/datetimepicker/validation/defaultcs.aspx

compare validator for DATE type

I want to compare 2 data in 2 textbox with DATE value,I used CompareValidator to compare them but it does not works for me how can I do? this is my CompareValidator code:
<asp:CompareValidator id="CompareValidator1"
runat="server" ErrorMessage="Invalid Date!" Type="Date"
ControlToValidate="SeconedDate_txt"
ControlToCompare="FirstDate_txt" Operator="GreaterThan"></asp:CompareValidator>
What format are you entering your dates in and what regional settings does your server have? Date comparison validation is Locale specific.
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Invalid DateTime"
ControlToValidate="TextBox1"
OnServerValidate="CustomValidator1_ServerValidate">
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
DateTime tempDateTime;
String textDateTime = TextBox1.Text;
if (DateTime.TryParse(textDateTime, out tempDateTime))
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
For this you will need ajax control toolkit, make sure you have downloaded the correct version for each .net framework.
<cc1:MaskedEditExtender ID="MaskedEditExtender5" runat="server" culturename="en-CA" mask="99/99/9999" masktype="Date" messagevalidatortip="true" argetcontrolid="txtEditExpireDate"></cc1:MaskedEditExtender>

Date format in RangeValidator

I am using RangeValidator to validate date enter in textbox and its working fine with default date format but now i want the date format in "dd/MM/yyy" but its generating excption with this date format. please provide me solution
my code:
in aspx page:
<asp:TextBox ID="txtrequiredby" runat="server" ></asp:TextBox >
<cc1:CalendarExtender ID="txtrequiredby_CalendarExtender" Format="dd/MM/yyyy"
runat="server" Enabled="True" TargetControlID="txtrequiredby" >
</cc1:CalendarExtender >
<asp:RangeValidator ID="rvreqby" runat="server" ErrorMessage="Required By Date
Greater Than or Equal to current date" ControlToValidate="txtrequiredby"
Display="Dynamic" Type="Date" ></asp:RangeValidator >
in codebehind:
rvreqby.MinimumValue = clsGeneral.FromSqlDate( DateTime.Now);
rvreqby.MaximumValue = clsGeneral.FromSqlDate( DateTime.Now.AddYears(200));
public static string FromSqlDate(DateTime date)
{
return date.ToString("dd/MM/yyyy");
}
MinimumValue & MaximumValue need to be set in the Page_PreRender event and appear to require the date format as "dd-MM-yy"...see last post on Rangevalidator Min Max Value error
protected void Page_PreRender(object sender, EventArgs e)
{
RangeValidator1.MinimumValue = DateTime.Now.Date.ToString("dd-MM-yy");
RangeValidator1.MaximumValue = DateTime.Now.Date.AddYears(90).ToString("dd-MM-yy");
}
Format of the MinimumValue and MaximumValue should be yyyy/MM/dd
Check documentation here:
https://msdn.microsoft.com/en-us/library/ydez7ad7(v=vs.110).aspx

Using the CompareValidator control to compare user input date with today's date

hey..i would like to compare the current date with the date entered by user..however, i'm encountering errors so far..
i tried something like this:
<asp:TextBox id="txtDate1" runat="server" />
<asp:CompareValidator runat="server" ErrorMessage="The date must be greater than today"
ControlToValidate="txtDate1" type="date"
ValuetoCompare="DateTime.Today.ToShortDateString()" />
and i got an error stating that the value of DateTime.Today.ToShortDateString() of the ValueToCompare property of "" cannot be converted to type 'date'
i also tried ValueToCompare="DateTime.Now.Date()" and i got the same error message.
please help me and i greatly appreciate it.
You're just using the ValueToCompare property as a literal string. You need to use ASP tags in it if you want to execute code to get a dynamic value. Try this:
<asp:comparevalidator runat="server"
errormessage="The date must be greater than today"
controltovalidate="txtDate1" type="date"
valuetocompare="<%# DateTime.Today.ToShortDateString() %>" />
Then in your Page_Load method, call Page.DataBind().
This will execute the databinder code when the page is loaded, and put the value in between the quotes.
<asp:CompareValidator ID="CompareValidator3" runat="server"
ControlToValidate="TextBox1" ErrorMessage="Date should be on or after today"
Operator="GreaterThanEqual" Type="Date">
</asp:CompareValidator>
In the page load event set the validator's value to compare as
CompareValidator3.ValueToCompare = DateTime.Now.ToShortDateString();
We can set the ValueToCompare in code behind
if (!Page.IsPostBack)
{
string currentDate = DateTime.Today.ToShortDateString();
Comparevalidator1.ValueToCompare = currentDate;
}
for the compare validator:
<asp:CompareValidator ID="Comparevalidator1" runat="server" ErrorMessage="The date must be greater than today"
Operator="GreaterThan" ControlToValidate="txtDate1" Type="date" Display="Dynamic" />
Why not use Page.DataBind?
Consider the following scenario. I need to display the gridview only on the click of the Action button. The datasource is defined declaratively. But, if I use Page.DataBind() it will show the grid even on the page load.
<form id="form1" runat="server">
<asp:TextBox ID="txtDate1" CssClass="firstBox" runat="server" Text=""></asp:TextBox>
<asp:CompareValidator ID="Comparevalidator1" runat="server" ErrorMessage="The date must be greater than today"
Operator="GreaterThan" ControlToValidate="txtDate1" Type="date" Display="Dynamic" />
<asp:Button ID="btnAction" class="submitButton" runat="server" Text="Action" OnClick="btnAction_Click" />
<asp:Button ID="btnDummy" class="submitButton" runat="server" Text="Dummy" OnClick="btnDummy_Click" />
<br />
<br />
<asp:GridView ID="GridView1" runat="server" DataSource="<%# EmployeesResult %>">
</asp:GridView>
</form>
Code behind
public partial class ThirdTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Page.DataBind();
if (!Page.IsPostBack)
{
string currentDate = DateTime.Today.ToShortDateString();
txtDate1.Text = currentDate;
Comparevalidator1.ValueToCompare = currentDate;
}
}
protected void btnAction_Click(object sender, EventArgs e)
{
GridView1.DataBind();
string value = GridView1.DataSource.ToString();
}
protected void btnDummy_Click(object sender, EventArgs e)
{
}
//Propertry
public List<Employee> EmployeesResult
{
get
{
List<Employee> employees = new List<Employee>();
employees.Add(new Employee { EmpID = 1, EmpName = "Emp1" });
employees.Add(new Employee { EmpID = 2, EmpName = "Emp2" });
return employees;
}
}
}
Try this.
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Date is required" ControlToValidate="txtmDate"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Date is not valid (MM.DD.YYYY)" ControlToValidate="txtDate" ValidationExpression="(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d" ></asp:RegularExpressionValidator>
The way user input the date (date format) is also Important. In here, I have used MM.DD.YYYY date format.
<asp:CompareValidator ID="CompareValidatorGreaterThanToday" runat="server" ErrorMessage="The date must be greater than today" ControlToValidate="txtDate" Type="date" Operator="GreaterThan" ValueToCompare="<%# DateTime.Today.ToShortDateString() %>" ></asp:CompareValidator>
Then in your Page_Load method (*.aspx.cs), call Page.DataBind().
Example:
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();
}
Try the below written :
<asp:CompareValidator runat="server" ErrorMessage="The date must be greater than today"
ControlToValidate="txtDate1" type="DateTime"
ValuetoCompare='<%# DateTime.Now.ToString("d") '%> />

Resources