End Date greater than Start Date Validation - javascript

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?

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);

Error to validate the start date and end date in php file

When we declare the java script the validation not applied and not fired an error wile the is same as input type i have declared the code in php file.
I have used Xammp server, running MySQL 5, PHP 7.6.2 and Apache 2.
<script type="text/javascript">
//Validation for Stratdate & Enddate for New Ticket creation form
$("#tedate").change(function () {
var objFromDate = document.getElementById("tsdate").value;
var objToDate = document.getElementById("tedate").value;
var FromDate = new Date(objFromDate);
var ToDate = new Date(objToDate);
if(FromDate > ToDate )
{
alert("Due Date Should Be Greater Than Start Date");
document.getElementById("tedate").value = "";
return false;
}
});
</script>
start date
<input type='date' id="tsdate" class="form-control col-md-6" placeholder="mm-dd-yyyy" name="startdate">
due date
<input type='date' id="tedate" class="form-control col-md-6" placeholder="Enter Due Date" name="enddate" required />
I want validate due date is greater than start date
Use strtotime function in php
if(strtotime($date1) < strtotime($date2)){
/* Code */
}
Use getTime() function which will convert the time into epoch format.For more details visit https://www.epochconverter.com/programming/#javascript
you can do the following to check in the frontend.
Javascript
$(".data-controller").change(function () {
var objFromDate = document.getElementById("tsdate").value;
var objToDate = document.getElementById("tedate").value;
var FromDate = (new Date(objFromDate).getTime()) / 1000;
var ToDate = (new Date(objToDate).getTime()) / 1000;
if (FromDate > ToDate) {
alert("Due Date Should Be Greater Than Start Date");
}
});
HTML
<input type='date' id="tsdate" class="form-control col-md-6 data-controller" placeholder="mm-dd-yyyy"
name="startdate"> // class data-controller added
<input type='date' id="tedate" class="form-control col-md-6 data-controller" placeholder="Enter Due Date"
name="enddate"
required/> // class data-controller added

How to show different time period on Sunday - Jquery datetimepicker

I would like to set a specific time period only on Sunday. So every other day the 'allowTimes' is from 18:00 to 22:30 but on sunday its 12:30 till 20:30. I am searching solution from last two days but haven't found it.
HTML
<div class="form-group">
<input type="text" id="date" name="txtDate" class="form-control" placeholder="Date">
</div>
<div class="form-group">
<input type="text" id="time" name="txtTime" class="form-control" placeholder="Time">
</div>
JQUERY
//Time Picker
$('#time').datetimepicker({
datepicker:false,
format:'H:i',
step:15,
allowTimes:['18:00','18:15','18:30','18:45','19:00','19:15','19:30','19:45','20:00','20:15','20:30','20:45','21:00','21:15', '21:30', '21:45', '22:00', '22:15','22:30']
});
// Date Picker
$('#date').datetimepicker({
timepicker:false,
format:'d/m/Y',
});
Your question is trickier than it seems because jQuery DateTimePicker in an instance and the fact that once initialized, you can't change the options.
But there always is a walk-around!
The trick here is to "destroy" the instance on the time input when the day number changes (0 for sunday to 6 for saturday) and reinitialise it with the right schedule. Now if the selected time does not exist in the new schedule, force the user to re-select the time.
Looks simple? See the code:
console.clear();
var schedule_week = ['18:00','18:15','18:30','18:45',
'19:00','19:15','19:30','19:45',
'20:00','20:15','20:30','20:45',
'21:00','21:15','21:30','21:45',
'22:00','22:15','22:30'];
var schedule_sunday = ['12:30','12:45',
'13:00','13:15','13:30','13:45',
'14:00','14:15','14:30','14:45',
'15:00','15:15','15:30','15:45',
'16:00','16:15','16:30','16:45',
'17:00','17:15','17:30','17:45',
'18:00','18:15','18:30','18:45',
'19:00','19:15','19:30','19:45',
'20:00','20:15','20:30'
];
var prev_dayNum;
var schedule_used = schedule_week; // Use the week schedule by default.
// Function to initialise the time picker input.
function initTime(){
$('#time').datetimepicker({
datepicker:false,
format:'H:i',
step:15,
allowTimes: schedule_used
});
}
// On load time initialisation.
initTime();
// Initialise the date input.
$('#date').datetimepicker({
timepicker:false,
format:'d/m/Y',
// On change callback
onChangeDateTime:function(dp,$input){
var dateVal = $input.val();
var timeVal = $('#time').val();
//console.log(dateVal +" - "+ (timeVal||"No Time"));
// Because of the d/m/Y format, have to process the date a bit to get the day number.
val = dateVal.split("/");
var dayNum = new Date(val[2]+"/"+val[1]+"/"+val[0]).getDay();
//console.log("dayNum: "+dayNum);
// if dayNum is zero (sunday), use sunday schedule... Else use the week schedule.
schedule_used = (dayNum == 0) ? schedule_sunday : schedule_week;
// If the dayNum changed.
if( prev_dayNum != dayNum ){
console.log("Changed day!");
// Re-initialise datetimepicker
$('#time').datetimepicker("destroy");
initTime();
// If the actual time value is not in schedule.
if($.inArray(timeVal,schedule_used) == -1){
console.log("Wrong time!");
// Clear the time value.
$('#time').val("");
// Focus the time input so it's obvious the user has to re-select a time.
$('#time').focus();
}
}
// Keep this dayNum in memory for the next time.
prev_dayNum = dayNum;
}
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.js"></script>
<div class="form-group">
<input type="text" id="date" name="txtDate" class="form-control" placeholder="Date">
</div>
<div class="form-group">
<input type="text" id="time" name="txtTime" class="form-control" placeholder="Time">
</div>
Now as you can see, the time schedule is different for sundays than the other days. And it "forces" the user to enter/re-enter a time only when what's entered does not fit the schedule.
I left the console logs uncommented in CodePen.

PHP: Date range selection automatically

I have 3 input fields all together.
Contract period: 1 years(for example)
start date : 30 - 1- 2012 (for example)
end date : ????
(Can we get the end date automatically according to the contract period mentioned, which mean if the date after 1 year is 30-1-2013 can we get it automatically in the third field after mentioning the first and second field).
Possible, using onSelect option of jQuery datepicker.
1) get the value of contract year and parse it as integer.
var addYears = parseInt($('#contract').val(), 10);
2) Split the selected date in startDate, as below
var t = date.split('/');
3) Now add the years and parse it as Date object.
var fin = new Date(parseInt(t[2], 10) + addYears, --t[0], t[1]);
Finally,
HTML:
In years only:
<input id="contract" type="text" />
<input id="start" type="text" />
<input id="end" type="text" />
JS:
$('#end').datepicker();
$('#start').datepicker({
onSelect: function (date, args) {
var addYears = parseInt($('#contract').val());
var t = date.split('/');
var fin = new Date(parseInt(t[2], 10) + addYears, --t[0], t[1]);
$('#end').datepicker("setDate", fin);
}
});
JSFiddle

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.

Categories

Resources