I have an ASP.Net form in which users can choose the date from Calendar Extender control, I have 2 fields for the date (FromDate & ToDate).
I want to validate the following using javascript:
FromDate should be always less than ToDate
FromDate & ToDate should not be less than today's date.
If both conditions are true, I would like then to call a method from the codebehind which will calculate the total number of days within the selected period excluding the weekends and display it to the user (this method works fine).
In the code below I tried __doPostBack to fire the codebehind method when the two previously mentioned conditions are met. It fires the codebehind method but then javascript variables becomes incorrect (compareDate variable is always increment on each function call & postback) and thus all the result becomes incorrect.
*Below is the current method I use to validate the date using Javascript, it's fired from OnClientDateSelectionChanged event from both textboxes's calendar extender controls *
<script type="text/javascript">
var fromDate = new Date();
var toDate = new Date();
function checkDate(sender, args) {
if (sender.get_id() == 'CalendarExtenderFrom') {
fromDate = sender._selectedDate;
}
else if (sender.get_id() == 'CalendarExtenderTo') {
toDate = sender._selectedDate;
}
// Check if selected date is less than today's date
var todayDate = new Date();
var year = todayDate.getFullYear();
var month = todayDate.getMonth();
var day = todayDate.getDate();
var dateOnly = new Date(year, month, day);
if (sender._selectedDate < dateOnly) {
alert("You cannot select a day earlier than today!");
sender._textbox.set_Value("");
return;
}
// Check if FromDate > ToDate
if (document.getElementById('TextBoxDateOfLeave').value != "" && document.getElementById('TextBoxDateOfReturn').value != "") {
var compareDate = new Date(fromDate.getFullYear(), fromDate.getMonth(), (fromDate.getDate()) + 1, 00, 00, 00, 00);
if (toDate < compareDate) {
alert("(Return Date) should be greater than (Travel Date)");
sender._textbox.set_Value("");
return;
}
}
// If both conditions are met
window.__doPostBack('__Page', '');
}
</script>
ASP.Net Controls:
<asp:TextBox ID="TextBoxDateOfLeave" runat="server" ClientIDMode="Static" ontextchanged="CalculateLeaveDays"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtenderFrom" runat="server" Enabled="True" Format="dd/MMM/yyyy" TargetControlID="TextBoxDateOfLeave" OnClientDateSelectionChanged="checkDate" />
<asp:TextBox ID="TextBoxDateOfReturn" runat="server" ClientIDMode="Static" ontextchanged="CalculateLeaveDays"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtenderTo" runat="server" Enabled="True" Format="dd/MMM/yyyy" TargetControlID="TextBoxDateOfReturn" OnClientDateSelectionChanged="checkDate" />
Please let me know if there is a way to achieve this.
Thank you,
Were you looking for something like this? I added a Fiddle here. I used the jquery ui date picker, but you can use any datepicker of your choice, provided the values are in 'yyyy/mm/dd' or 'mm/dd/yyyy' I think
Related
I have a textbox: txtDepartureDate where a user can select the departure date. If the selected date is before today, then I was to show an error message. I have tried using the moment library in Javascript to achieve this and also used the oninput() event handler. I am trying to subtract today's date with the departure date to get the total number of days and if this is less than or equal to zero, then lblError should display the error message. The validation part is not working for me.
Textbox:
<asp:TextBox ID="txtDepartureDate" runat="server" ForeColor="Gray" onfocus="txtOnFocusDeparture(this)" onblur="txtOnBlurDeparture(this)" oninput="oninputDeparture()" AutoPostBack="True">DEPARTURE DATE</asp:TextBox>
Script:
<script type="text/javascript">
function oninputDeparture() {
var inputDate = moment(document.getElementById('txtDepartureDate').value, 'DD/MM/YYYY');
var todayDate = moment().format('DD/MM/YYYY');
var lblError = document.getElementById('lblError');
var daysDiff = todayDate.diff(inputDate, 'days');
if (daysDiff <= 0) {
lblError.innerText = "Departure Day should be after today";
}
else {
lblError.innerText = "";
}
}
</script>
This is how it is done:
var inputDate = moment([1990, 0, 01]);
var todayDate = moment().toDate();
inputDate.diff(todayDate, 'days')
You have to get entered input date in the above format.
I am using this code for the validation, it works fine when using the default datepicker in html but when typing the date manually, it's not properly working. For example, when I type a start date then proceed to the endate, the year in the end date automatically reads only the first number of "2019" so you can't finish typing properly since it alerts and can't compare properly.
<input type="date" id="StartDate" />
<input type="date" id="EndDate" />
<script>
console.clear();
var startDate = document.getElementById("StartDate").value;
var endDate = document.getElementById("EndDate").value;
function compareDates() {
if ((Date.parse(endDate) <= Date.parse(startDate))) {
alert("End date should be greater than Start date");
document.getElementById("EndDate").value = "";
}
}
startDate.addEventListener('input', compareDates);
endDate.addEventListener('input', compareDates);
</script>
Any tips?
In my form , I have 3 fields.
<input name="course_duration" id="course_duration" type="text"> (A numeric value which denotes 'Weeks'
<input name="course_start" id="course_start" type="text">
<input name="course_end" id="course_end" type="text">
I am using datepicker jquery and I want to fillup course_end date automatically by adding number of weeks from value inserted in course_duration field + course_start date
currently I am using following javascript code to popup calendar and selecting dates for course_start and course_end manually.
<script type="text/javascript">
$(document).ready(function() {
$('#course_start').datepicker({dateFormat: 'yy-mm-dd'});
$('#course_end').datepicker({dateFormat: 'yy-mm-dd'});
});
</script>
JSFIDDLE
// Get the week from course_duration
var weeks = $('#course_duration').val();
// Get the selected date from startDate
var startDate = $('#course_start').datepicker('getDate');
var d = new Date(startDate);
// Add weeks to the selected date, multiply with 7 to get days
var newDate = new Date(d.getFullYear(), d.getMonth(), d.getDate() + weeks * 7);
// Set the new date to the course endDate
$('#course_end').datepicker('setDate', newDate);
Demo
I am new to Javascript programming and I am trying to validate a date entered into an <input> from a calender snippet which is obtained from an external Javascript file. I am trying to validate the date to check if the user entered a past date. If the entered date is a past date, then I need to print a warning message to enter a valid date in future period.
I accept input date field in following HTML code:
<input size="12" id="inputField" name="inputField" autofocus="" type="date" oninput="return dateValidate(inputField)"/>
My Javascript function to validate input date is:
<script type="text/javascript">
function dateValidate(inputField)
{
var v2 = document.getElementById('inputField');
var pickeddate = new Date(v2.Value);
todayDate = new Date();
if(pickeddate > todayDate){
return true;
} else {
alert("Enter a valid Date");
}
}
But this code doesn't seem to be working. I want this Javascript function to be run when I enter a past date in the <input> field and tab out. I want to validate date when it is entered in the field, not when the form is submitted.
It is not working since there is a issue in your code, just replace this:
var pickeddate = new Date(v2.Value);
with this:
var pickeddate = new Date(v2.value); // 'value' should be in lower case
Since, it was not correct, the pickeddate was always undefined and code didn't worked.
You may try this
HTML
<input size="12" id="inputField" name="inputField" autofocus="" type="date" onblur="return dateValidate(this)"/>
JS
function dateValidate(inputField)
{
var pickeddate = new Date(inputField.value);
var todayDate = new Date();
if( pickeddate > todayDate )
{
return true;
}
else
{
alert("Enter a valid Date");
}
}
DEMO.
I have the following code to compare two dates with the following conditions
Scenario:
On load there are two text boxes (FromDate, ToDate) with Ajax calendar extenders.
On load From Date shows today's date.
when date less than today was selected in both text boxes(FromDate, ToDate), it alerts user saying "You cannot select a day earlier than today!"
When ToDate's Selected date < FromDate's Selected Date, alerts user saying "To Date must be Greater than From date." and at the same time it clears the selected Date in ToDate Text box.
Codeblock:
ASP.NET , AJAX
<asp:TextBox ID="txtFrom" runat="server"
ReadOnly="true"></asp:TextBox>
<asp:ImageButton ID="imgBtnFrom" runat="server" ImageUrl="~/images/Cal20x20.png" Width="20" Height="20" ImageAlign="TextTop" />
<asp:CalendarExtender ID="txtFrom_CalendarExtender" PopupButtonID="imgBtnFrom"
runat="server" Enabled="True"
OnClientDateSelectionChanged="checkDate"
TargetControlID="txtFrom" Format="MMM d, yyyy">
</asp:CalendarExtender>
<asp:TextBox ID="txtTo" runat="server"
ReadOnly="true"></asp:TextBox>
<asp:ImageButton ID="imgBtnTo" runat="server" ImageUrl="~/images/Cal20x20.png" Width="20" Height="20" ImageAlign="TextTop" />
<asp:CalendarExtender ID="txtTo_CalendarExtender"
OnClientDateSelectionChanged="compareDateRange"
PopupButtonID="imgBtnTo"
runat="server"
Enabled="True" TargetControlID="txtTo"
Format="MMM d, yyyy">
</asp:CalendarExtender>
<asp:HiddenField ID="hdnFrom" runat="server" />
<asp:HiddenField ID="hdnTo" runat="server" />
C# Code
protected void Page_Load(object sender, EventArgs e)
{
txtFrom.Text = string.Format("{0: MMM d, yyyy}", DateTime.Today);
if (Page.IsPostBack)
{
if (!String.IsNullOrEmpty(hdnFrom.Value as string))
{
txtFrom.Text = hdnFrom.Value;
}
if (!String.IsNullOrEmpty(hdnTo.Value as string))
{
txtTo.Text = hdnTo.Value;
}
}
}
JavaScript Code
<script type="text/javascript">
function checkDate(sender, args) {
document.getElementById('<%=txtTo.ClientID %>').value = "";
if (sender._selectedDate < new Date()) {
alert("You cannot select a day earlier than today!");
sender._selectedDate = new Date();
// set the date back to the current date
sender._textbox.set_Value(sender._selectedDate.format(sender._format));
//assign the value to the hidden field.
document.getElementById('<%=hdnFrom.ClientID %>').value = sender._selectedDate.format(sender._format);
//reset the to date to blank.
document.getElementById('<%=txtTo.ClientID %>').value = "";
} else {
document.getElementById('<%=hdnFrom.ClientID %>').value = sender._selectedDate.format(sender._format);
}
}
function compareDateRange(sender, args) {
var fromDateString = document.getElementById('<%=txtFrom.ClientID %>').value;
var fromDate = new Date(fromDateString);
if (sender._selectedDate < new Date()) {
alert("You cannot select a Date earlier than today!");
sender._selectedDate = "";
sender._textbox.set_Value(sender._selectedDate)
}
if (sender._selectedDate <= fromDate) {
alert("To Date must be Greater than From date.");
sender._selectedDate = "";
sender._textbox.set_Value(sender._selectedDate)
} else {
document.getElementById('<%=hdnTo.ClientID %>').value = sender._selectedDate.format(sender._format);
}
}
</script>
Error Screen(Hmmm :X)
Now in ToDate, when you select Date Earlier than today or Date less than FromDate, ToDate Calendar shows NaN for Every Date and ,0NaN for Year
It looks like the format method is assuming a numeric argument, but is being passed a string argument. Comment out both else blocks to confirm this. The if blocks seem to always return false for the following reasons:
Since the two dates are strings, their lengths are compared, not their dates
Use Date.parse() on each date to do a numeric comparison
Validate your date format with a hardcoded value, e.g. Date.parse("May 1, 1999")