Consider a case where we have a text box with AJAX Calendar Extender to accept dates from the user. We have to restrict the dates entered by the user based on two conditions.
1) If the date entered is less than 90 days I have to Display the error message “Please select a date >=” (Today’s date – 90 days )
2) If the date enter is future date I have to display the error message “Information is not available for future dates”
Create an Ajax Enabled website
Add a text box, Ajax calendar extender and a custom validation control<asp:TextBox ID="TextBox1" runat="server" >asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="TextBox1">
cc1:CalendarExtender>
<asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="ValidateFun" ControlToValidate="TextBox1" ErrorMessage="CustomValidator"> asp:CustomValidator>
JavaScript function
<script type="text/javascript" language="javascript">
function ValidateFun(source, arguments)
{
//get the date that user has entered
var DateChooser = document.getElementById("TextBox1");
var dt = new Date(DateChooser.value);
//today's date
var today = new Date();
//valid date i.e. today's date - 90 days
var validDate = new Date();
validDate.setDate(today.getDate() - 90);
//calculate the number of milliseconds in 1 day
var one_day = 1000*60*60*24;
//calculate the difference in days for the value entered by the user and today's date
var diff = Math.floor((today.getTime() - dt.getTime())/(one_day));
if(diff > 90)// if the date entered is beyond 90 days from today
{
source.innerText = "Please enter a date >= " + (validDate.getMonth()+1)+"/"+validDate.getDate()+"/"+validDate.getFullYear();
arguments.IsValid = false;
}
else if(diff < 0)// if we entered a future date
{
source.innerText = "Information is not available for future dates";
arguments.IsValid = false;
}
else
arguments.IsValid = true;
}
script>
0 comments:
Post a Comment