How to do date validation with moment library in JavaScript? - javascript

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.

Related

Limit the date to today and block the previous dates

I am beginner in JavaScript, I know the subject exists on StackOverFlow as here below but I don't understand.
Compare two dates with JavaScript
I would like to handle the previous dates for example: We are on 28-05-2020, if the user enters on 27-05-2020 an error message should appear.
For information, I am obliged to use JavaScript to handle the dates.
function validation()
{
const date_start = document.getElementById('date_start').value;
const inputDate = new Date(date_start);
const dayFromImputDate = inputDate.getFullYear(); // previous day
const now = new Date();
const dateNow = now.getFullYear();
if(dayFromImputDatee < dateNow) {
document.getElementById('date_startError').innerHTML = " ** Error date ! ";
return false;
}
if(date_start == ""){
document.getElementById('date_startError').innerHTML = " ** date empty ! ";
return false;
}
console.log("Date is valid");
return true;
}
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Titre de la page</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form action="#" onsubmit="return validation()" >
<br>
<label>Date start : </label>
<br>
<input type="date" name="date_start" id="date_start">
<br>
<span id="date_startError"></span>
<br>
<input type="submit" value="ok">
</form>
</body>
</html>
Thank you very much for your help and your time.
You can check if input date is less than today's date using < operator
const form = document.querySelector('form');
const error = document.getElementById('date_startError');
function validation(event) {
event.preventDefault();
const startDate = form.elements['date_start'].value;
if (!startDate) {
error.innerHTML = " ** date empty ! ";
return;
}
const inputDate = new Date(startDate).getDate();
const today = new Date().getDate();
if (inputDate < today || !inputDate.valueOf()) {
error.innerHTML = " ** Error date ! ";
return;
}
error.innerHTML = "date is valid";
}
<form action="#" onsubmit="validation(event)">
<br>
<label>Date start : </label>
<br>
<input type="date" name="date_start" id="date_start" placeholder="2020-05-28">
<br>
<span id="date_startError"></span>
<br>
<input type="submit" value="ok">
</form>
Because HTML5 already has min and max attributes for the date input type, you don't need to implement a separate validation function to accomplish this. Here is a simpler way:
var date = new Date();
var iso_date = date.toISOString().substring(0, 10);
document.getElementById("date_start").setAttribute('min', iso_date);
Basically, you just get a new Date() object, extract and format it into an ISO 8601 date format, and set it into the min attribute. This also limits the browser selection calendar to future dates only.
If I understand the problem correctly you are trying to restrict a date form input to the current day or some future date.
To check whether a date is valid you could do this:
let earliestPossibleDate = new Date(
now.getFullYear(), now.getMonth(), now.getDate()
);
let isValidDate = date_start >= earliestPossibleDate
Three things:
You need to get your Current Date and set time to start of day.
You need to get your Selected Date and set time to start of day
Compare whether Selected Date is Greater or Equal to the Current Date.
Note that when you compare dates, you need to also consider the time.
Most calendar tools, include the time as a response to the selected date. You need to be aware of that.
This doesn't include other date validations. This will only solve the current problem at hand. Hope this helps! =)
const isValidDate = (selectedDate) => {
const currentDate = new Date();
// reset to start of day
currentDate.setHours(0);
currentDate.setMinutes(0);
currentDate.setSeconds(0);
currentDate.setMilliseconds(0);
const newDate = new Date(selectedDate);
newDate.setHours(0);
newDate.setMinutes(0);
newDate.setSeconds(0);
newDate.setMilliseconds(0);
return newDate.getTime() >= currentDate.getTime();
}
To use, simply throw the selected date in the function. Should return true if the date is greater or equal to the date today.
isValidDate(selectedDateFromDatePicker);

set a value of select option field from the datepicker field

i have a booking form with checkin, nights, and chckout
the user select chckin date, and after that he choose number of nights, its reflect on the checkout field date
(if the checkin is to 08/08/19 and the user select 4 nights the checkout will be 12/08/19)
now.. what i want is if the user change the checkout date its reflect on the nights value
i already did the change from the nights select to checkout filed
$( ".nights" )
.change(function () {
$( this ).each(function() {
var nights = $('.nights-field').val();
var nightsVAr = "+" + nights + "d";
$( ".checkout-field" ).datepicker().datepicker("setDate", nightsVAr);
});
})
.change();
what i have truble with is the checkout field to nights
i need to calculate somehow the date of checkout minus the checkin and set the number of nights in the select field
try to use momentjs lib,
it will be something like this
var from = moment(fromDate);
var to = moment(toDate);
var nights =from.diff(to, 'days')
If you manipulate a lot of date I recommend using moment. Some other libraries as FullCalendar already use it.
Jquery solution :
Idea : getting the date in your form, gettings it timestamps, do the diff and convert the ms in day unit.
Using Math.round to get a int & Math.abs() for getting always a positive number.
$(document).ready(() => {
var arrival = $("input#arrival");
var departure = $("input#departure");
var msInDay = 1000 * 60 * 60 *24; // number of ms in a day;
$("input[type='date']").change(() => {
if (arrival.val() && departure.val()) {
dateArrival = new Date(arrival.val());
dateDeparture = new Date(departure.val());
var days = Math.round(Math.abs((dateArrival.getTime() - dateDeparture.getTime())) / (msInDay)); // getting time stamps of each date.
console.log("nights :" +days);
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" id="arrival">
<input type="date" id="departure">
Here I provide code which set nights field when we change checkout date field with simple jquery code with date and math function.
If your checkout date field is less than your checkin date field, then it will set nights field as 0 and show console log with error message.
$(".checkout-field")
.change(function () {
var nights = $('.nights-field').val();
var checkInDate = new Date($(".checkin-field").val());
var checkOutDate = new Date($(".checkout-field").val());
if(checkOutDate <= checkInDate) {
console.log("error dates are not valid");
$(".nights-field").val(0);
}
else {
var diffDate = checkOutDate - checkInDate;
var days = Math.floor(((diffDate % 31536000000) % 2628000000)/86400000);
$(".nights-field").val(days);
}
})

how to add days / weeks from separate field in start date to get end date in datepicker?

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

Javascript to validate date entered

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.

Validation Dates using Javascript & ASP.Net

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

Categories

Resources