check RadDateTimePicker value against current system date time value - asp.net

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

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>

Validation for date with CompareValidator

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 !

Asp.net validation error message to change labels text

I am using asp.net validation controls for validating user input. What i want is to change the label text with the error message generated by the validation control.
<asp:Label ID="Label1" runat="server" Text="Whats your name"></asp:Label>
<asp:TextBox ID="nameB" Width="322px" Height="30px" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ValidationGroup="business" runat="server" ErrorMessage="Please tell us your name." ControlToValidate="nameBuisness" CssClass="errMsg" Display="Dynamic"></asp:RequiredFieldValidator>
Thank you.
One way is to handle the submit-button's OnClientClick-event and call a javascript function like:
<script type="text/javascript">
function displayValidationResult() {
// Do nothing if client validation is not available
if (typeof (Page_Validators) == "undefined") return;
var LblName = document.getElementById('LblName');
var RequiredName = document.getElementById('RequiredName');
ValidatorValidate(RequiredName);
if (!RequiredName.isvalid) {
LblName.innerText = RequiredName.errormessage;
}
}
</script>
<asp:Label ID="LblName" runat="server" Text="Whats your name"></asp:Label>
<asp:TextBox ID="TxtNameBusiness" Width="322px" Height="30px" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredName" ValidationGroup="business"
runat="server" ErrorMessage="Please tell us your name." ControlToValidate="TxtNameBusiness"
CssClass="errMsg" Display="None"></asp:RequiredFieldValidator>
<asp:Button ID="BtnSumbit" runat="server" Text="Submit"
OnClientClick="displayValidationResult()" ValidationGroup="business" />
I've used some of the few ASP.NET client validation methods available. I've also renamed your controls to somewhat more meaningful and added a submit-button.
ASP.NET Validation in Depth
If your requirement is that you want to do this validation using the built-in ASP.Net validation controls, then you will need to use the ASP.Net CustomValidator control. This cannot be done using the ASP.Net RequiredFieldValidator control. To do the validation you specified, put a CustomValidator control on on your page so that the markup looks like this:
<asp:Label ID="Label1" runat="server" Text="Whats your name"></asp:Label>
<asp:TextBox ID="nameB" Width="322px" Height="30px" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustValidator" runat="server" ControlToValidate="nameB"
ValidateEmptyText="true" ErrorMessage="Please tell us your name."
onservervalidate="CustValidator_ServerValidate" Display="none" >**</asp:CustomValidator>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" CausesValidation="true" />
You then need to write your custom validator. The server-side validation code looks like this:
protected void CustValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
if (string.IsNullOrWhiteSpace(args.Value))
{
Label1.Text = CustValidator.ErrorMessage;
args.IsValid = false;
}
else
{
Label1.Text = "Whats your name";
args.IsValid = true;
}
}
This custom validator will give you the behavior you desire.
In general when you use a CustomValidator control, you should do both server-side validation (for security) and client-side validation (for a better UI experience). To get client-side validation, you will need to write a client-side function in javascript and/or jQuery to do similar validation and then assign it to the ClientValidationFunction of the custom validator.
Further information on the CustomValidator control can be found in the MSDN documentation.

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>

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