JavaScript validating datetime-local from form - javascript

I have an html form which allows for a taxi booking, but it shouldn't allow bookings back in time! so the time must be current or in the future.
Here is the form, I use datetime-local.
/* Here is the JavaScript validation for the datetime-local. */
var dateTime = document.getElementById("dateTime").value;
if (dateTime == "" || dateTime == null) {
booking.dateTime.focus();
document.getElementById("dateMessage").innerHTML = "Please select a date AND time, thankyou.";
return valid = false;
} else {
document.getElementById("destinationMessage").innerHTML = "";
}
```
<form id="booking" action="">
<div id="firstNameMessage" class="red"></div>
<span class="red">*</span>First Name:
<input type="text" name="firstName" id="firstName">
<br>
<div id="lastNameMessage" class="red"></div>
<span class="red">*</span>Last Name:
<input type="text" name="lastName" id="lastName">
<br>
<div id="numberMessage" class="red"></div>
<span class="red">*</span>Contact Number:
<input type="text" name="number" id="number">
<br>
<div id="unitMessage" class="red"></div>
Unit Number(optional):
<input type="text" name="unit" id="unit">
<br>
<div id="streetNumberMessage" class="red"></div>
<span class="red">*</span>Street Number:
<input type="text" name="streetNumber" id="streetNumber">
<br>
<div id="streetNameMessage" class="red"></div>
<span class="red">*</span>Street Name:
<input type="text" name="streetName" id="streetName">
<br>
<div id="pickupMessage" class="red"></div>
<span class="red">*</span>Suburb:
<input type="text" name="pickupSuburb" id="pickupSuburb">
<br>
<div id="destinationMessage" class="red"></div>
Destination Suburb<span class="red">*</span>:
<input type="text" name="destinationSuburb" id="destinationSuburb">
<br>
<div id="dateMessage" class="red"></div>
Pick-Up Date and Time<span class="red">*</span>:
<input type="datetime-local" name="dateTime" id="dateTime">
<br>
<br>
<input type="button" value="Submit"
onclick="getData('bookingprocess.php','message', firstName.value, lastName.value, number.value, unit.value, streetNumber.value, streetName.value, pickupSuburb.value, destinationSuburb.value, dateTime.value)" />
<input type="reset" value="Reset">
</form>
How can I make it check for being the current time or in the future? (Basically disabling past entries).

Please use input type = "date" instead of date-time. Probably no more supported by browsers.
Please refer this link
Now to set min date you cn use the following snippet
//Get today's date and split it by "T"
var today = new Date().toISOString().split('T')[0];
document.getElementById("dateTime").setAttribute('min', today);
DEMO

You can just compare dates by > and <. Make sure the dates in the same timezone though.
var dateTimeStr = document.getElementById("dateTime").value;
var dateTime = convertDateToUTC(new Date(dateTimeStr));
var now = new Date();
if (isNaN(date.getTime()) || date <= now) {
booking.dateTime.focus();
document.getElementById("dateMessage").innerHTML = "Please select a date AND time in the future, thankyou.";
return valid = false;
} else {
document.getElementById("destinationMessage").innerHTML = "";
}
function convertDateToUTC(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
JS Fiddle

You should use a jquery or bootstrap calendar. It is ideal for this situation. It is also very easy for the user to pick up the date this way.
You have all configuration options in such calendars for e.g. assigning culture, date format, mindate, maxdate etc.
Also keep in mind to pick the date from server and set it as mindate in javascript since the datetime might be wrong on client computer.

Related

Add a number of day for a given date

I would like to add a number of day to the date that I give to my form then display it in an empty input.
<div class="col">
<input type="date" [(ngModel)]="date" />
<input type="number" min="1" max="31" [(ngModel)]="day"/>
</div>
<div class="col">
<input type="button" value="Calculate" (click)="addDays()"/>
</div>
<div class="col">
<input type="text" [(ngModel)]="result"/>
</div>
The code behind
day: number;
date: Date;
result: Date;
addDays(){
this.result = this.date.setDate(this.date + this.day);
console.log(this.result);
}
I get an error: this.date.setDate is not a function because I can't add a number to a date. I checked some topics but didn't get solutions.
You have to do something like this:
function addDays(date, days) {
var newDate = new Date(date);
newDate.setDate(newDate.getDate() + days);
return newDate;
}

how can i fix my javascript calculation which is not working?

the problem is the "total price" is not working.when i pick the "pickup date" and "drop date" it will show the value in the input form. i have to key in the number in "number of days" then the total price will calculate. i need the "total of price" is auto calculate. i have try various event of javascript. here i will attach my code. hope someone will help me. thanks in advance.
function sum() {
var txtFirstNumberValue = document.getElementById('num1').value;
var txtSecondNumberValue = document.getElementById('numdays2').value;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('num3').value = result;
}
}
function GetDays() {
var dropdt = new Date(document.getElementById("drop_date").value);
var pickdt = new Date(document.getElementById("pick_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
if (document.getElementById("drop_date")) {
document.getElementById("numdays2").value = GetDays();
}
}
<label for="total">Price per day:</label>
<input type="text" name="price" id="num1" onkeyup="sum();" value="3" readonly>
<div id="pickup_date">
<p><label class="form">Pickup Date:</label>
<input type="date" class="textbox" id="pick_date" name="pickup_date" onchange="cal()" /></p>
</div>
<div id="dropoff_date">
<p><label class="form">Dropoff Date:</label>
<input type="date" class="textbox" id="drop_date" name="dropoff_date" onchange="cal()" /></p>
</div>
<div id="reserve_form">
<div id="numdays"><label class="form">Number of days:</label>
<input type="text" id="numdays2" name="numdays" oninput="sum();" />
<label for="total">Total Price (RM)</label>
<input type="text" name="test" placeholder="Total Price" value="" id="num3">
i expect that the total price can automatically calculate.
You just need to make sure your sum function (or in the example just cal) is being called when your inputs are complete and valid. Since you may want to restrict the user from manually setting the number of days I've demonstrated how you might do this by firing a change event programmatically. It's also current practice to attach events to elements programmatically instead of using the inline HTML5 event notation (e.g. "onchange=foo"), see Why are inline event handler attributes a bad idea in modern semantic HTML?
function setDate(event) {
var days = getDays();
// if the number of days is valid
if (!isNaN(days)) {
var nod = document.getElementById("numdays2");
nod.value = days;
// programmatically setting a value will not fire a change event
nod.dispatchEvent(new Event("change"));
}
}
function getDays() {
// returns NaN if either date does not hold a valid date
var dropdt = new Date(document.getElementById("drop_date").value);
var pickdt = new Date(document.getElementById("pick_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
var pricePerDay = document.getElementById("pricePerDay").value;
if (0 == (pricePerDay = parseInt(pricePerDay))) { return } // TODO needs to handle decimal values
document.getElementById("total").value = parseInt(document.getElementById("numdays2").value) * pricePerDay;
}
function init() {
document.getElementById("drop_date").addEventListener("change", setDate);
document.getElementById("pick_date").addEventListener("change", setDate);
document.getElementById("numdays2").addEventListener("change", cal);
}
document.addEventListener("DOMContentLoaded", init);
<label for="total">Price per day:</label>
<input type="text" name="price" id="pricePerDay" value="" placeholder="Manually enter a value">
<div id="pickup_date">
<p><label class="form">Pickup Date:</label>
<input type="date" class="textbox" id="pick_date" name="pickup_date" /></p>
</div>
<div id="dropoff_date">
<p><label class="form">Dropoff Date:</label>
<input type="date" class="textbox" id="drop_date" name="dropoff_date" /></p>
</div>
<div id="reserve_form">
<div id="numdays"><label class="form">Number of days:</label>
<!-- numdays2 is readonly to ensure the date pickers are used -->
<input type="text" id="numdays2" name="numdays" readonly placeholder="Select dates above" />
<label for="total">Total Price (RM)</label>
<input id="total" type="text" readonly name="test" placeholder="Total Price" value="" id="num3">
</div>
</div>

Face NaN result when calculating time difference with javascript

I'm a newbie and still at the beginner level of PHP, Javascript, Codeigniter. I'm facing an unexpected result when I try to calculate the time difference between two 12 hours format time inputs.
Here is the HTML,JS
function hitungjam() {
var start = new Date($('#inputJammulai'));
var end = new Date($('#inputJamselesai'));
var s = start.toTimeString();
var e = end.toTimeString();
var diff = e - s;
var jam = Math.floor(diff/1000/60/60);
$('#inputSelisih').val(jam);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div class="form-group">
<div class="form-row">
<div class="col-md-4">
<label for="inputJammulai">Start</label>
<!-- <div class="form-label-group"> -->
<input type="time" name="inputJammulai" id="inputJammulai" class="form-control" required="required">
<!-- </div> -->
</div>
<div class="col-md-4">
<label for="inputJamselesai">End</label>
<!-- <div class="form-label-group"> -->
<input type="time" name="inputJamselesai" id="inputJamselesai" onchange="javascript: hitungjam();" class="form-control" required="required">
<!-- </div> -->
</div>
</div>
</div>
RESULT
start 09:00 AM
end 11:30 AM
the result is NaN.
WHAT EXPECTED RESULT
start at 09:00 AM, end at 11:30 AM, the result is 2,5
Oh FYI, before I write down this question I've done a search and tried many solutions given from StackOverflow but doesn't work on my problem. That's why I'm asking now.
Can anyone here help me to find out the solution? Thank you
Here is couple of things First in order to get the value from the input use val() which was missing. Secondly the output from the input is a string, so use parseInt to convert it to number before doing mathematical operations
Using split to get the numbers from the input since the input will be like 9:00 for 9:00AM or 23:30 for 11:30PM.
function hitungjam() {
var start = $('#inputJammulai').val();
var end = $('#inputJamselesai').val();
let diff = toMins(end) - toMins(start);
let jam = `${Math.floor(diff/60)}:${diff%60}`;
$('#inputSelisih').val(jam);
}
function toMins(time) {
let splitTime = time.split(":");
return (parseInt(splitTime[0], 10) * 60) + parseInt(splitTime[1], 10)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<div class="form-row">
<div class="col-md-4">
<label for="inputJammulai">Start</label>
<!-- <div class="form-label-group"> -->
<input type="time" name="inputJammulai" id="inputJammulai" class="form-control" required="required">
<!-- </div> -->
</div>
<div class="col-md-4">
<label for="inputJamselesai">End</label>
<!-- <div class="form-label-group"> -->
<input type="time" name="inputJamselesai" id="inputJamselesai" onchange="javascript: hitungjam();" class="form-control" required="required">
<!-- </div> -->
</div>
</div>
</div>
<input id='inputSelisih'>
I have done some modifications to your original code so you can get a base working example, I will try to explain some of these:
1) You was not getting the values from your inputs, you need to use .val() for this.
2) You can't make a difference between strings and expect a number as result. Instead of this, I have splited the obtained values from the inputs into hours and minutes. Then we create new Date objects with current time and set the respective hours and minutes to they. Finally, we can use difference within the Date.getTime() of each Date.
3) Math.floor() will return an integer, but you want a number with decimals, so instead of this I use toFixed(1) to get a decimal number (as string) with one digit after the dot.
Base Example:
function hitungjam()
{
var [h1, m1] = $('#inputJammulai').val().split(":");
var [h2, m2] = $('#inputJamselesai').val().split(":");
var start = new Date(), end = new Date();
start.setHours(h1);
start.setMinutes(m1);
end.setHours(h2);
end.setMinutes(m2);
var diff = end.getTime() - start.getTime();
var jam = (diff / 1000.0 / 60 / 60).toFixed(1);
$('#inputSelisih').val(jam);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="time" name="inputJammulai" id="inputJammulai" class="form-control" required="required">
<input type="time" name="inputJamselesai" id="inputJamselesai" onchange="javascript: hitungjam();" class="form-control" required="required">
<label>Difference (hours):<label>
<input type="text" id="inputSelisih">

JavaScript Date of birth under 18

Is there a way to perform validation on the full date of birth (dd/mm/yyyy) to establish if the user is under 18 years. Most of the tutorials I found only shows me how to do it if the user age (not DOB) is under 18.
By the way I'm also using input type of "date" for my DOB textbox.
HTML
<body>
<header class="v-header container">
<div class="fullscreen-backgorund-Booking">
</div>
<div>
<ul>
<li>Home</li>
<li>McLaren Vale</li>
<li>Barossa</li>
<li>Clare</li>
<li>Online Booking</li>
<div id="mySidenav" class="sidenav">
×
Home
McLaren
Barossa
Clare
Online Booking
</div>
<span id="sidebtn" onclick="openNav()">☰</span>
</ul>
</div>
<div class="header-overlay"></div>
<div class="header-content" style="width: 100%;">
<!-- width... is not working in external css... why?-->
<h1 style="margin-top: -100px;">Online Booking</h1>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
<input type="text" name="fname" placeholder="Firstname"> Date of Brith
<input type="date" name="DoB" placeholder="Date of Birth">
<input type="text" name="TelNumber" placeholder="Telephone number">
<input type="email" name="email" placeholder="Email"> Date of Tour
<input type="date" name="DoT" placeholder="Date of tour (dd.mm.yyyy)">
<form action="" id="calculate" onsubmit="return false;">
<input type="text" placeholder="Number of Travellers" id="val" name="val" value="" />
<label class="radiolabel">
<input type="radio" name="button" value="100">McLaren</label>
<label class="radiolabel">
<input type="radio" name="button" value="150">Barossa</label>
<label class="radiolabel">
<input type="radio" name="button" value="90">Clare</label>
<div id="result" style="display: block;">
Result:</div>
<input type="submit" id="submit" value="Submit" onclick="endresult(document.forms['myForm'].elements['button']);">
</div>
</form>
</div>
I would first calculate the age and then check if he is over 18. Here is a codesnippet.
var birthday1 = new Date("2015-03-25");
var birthday2 = new Date("1994-03-25");
function isOverEighteen(birthday) {
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs);
var age = Math.abs(ageDate.getUTCFullYear() - 1970);
if(age > 17){
return true;
}else{
return false;
}
}
console.log(isOverEighteen(birthday1));
console.log(isOverEighteen(birthday2));
There are many similar questions, but none seem to have good answers.
Rather than calculating age (which is actually tricker than many expect), you can either add 18 years to the date of birth and see if it's before today, or subtract 18 years from today and see if it's after the date of birth.
// Subtract 18 years from now and see if greater than birth date
function over18(birthDate) {
var now = new Date();
var m = now.getMonth();
now.setFullYear(now.getFullYear() - 18);
// deal with today being 29 Feb
if (m != now.getMonth()) now.setDate(0);
return now > birthDate;
}
// Some tests
var opts = {day: '2-digit', month:'short', year:'numeric'};
[new Date(2000,1,29), // 29 Feb 2000
new Date(2000,0,20), // 20 Jan 2000
new Date(2000,0,19), // 19 Jan 2000
new Date(2000,0,18), // 18 Jan 2000
new Date(1999,0,1) // 1 Jan 1999
].forEach(function(d) {
console.log(d.toLocaleString('en-GB', opts), over18(d));
});
A simple improvement is to allow an optional checkDate that defaults to today and use that instead of now.

Javascript Date Validation on Form Input

Am trying to validate the date on a form so that user cannot select a date in the past, or that checkout date is greater than checkin date
<form action="form2email.php" method="post" name="form" target="_blank" onSubmit="return validate(form);">
<fieldset id="user-1">
<h2>
<img src="images/booking-enquiry.png" width="160" height="20" />
</h2>
<label for="name">Name:</label>
<input name="name" type="text" />
<label for="email" class="required">Email:</label>
<input type="text" name="email" size="8" id="email" />
</fieldset>
<fieldset id="user-2">
<h2> </h2>
<label for="Phone" class="required">Phone:</label>
<input type="text" name="Telephone_Number" id="Phone" />
<label for="Accommodation Type" class="required">Accommodation Type:</label>
<select id="room_type" name="Accommodation Type">
<option value="Villa">Villa</option>
<option value="1 Bed Apartment">1 Bed Apartment</option>
<option value="2 Bed Apartment">2 Bed Apartment</option>
</select>
</fieldset>
<fieldset id="user-3">
<h2> </h2>
<label for="Check-in-Date" class="required">Check-in Date:</label>
<script>
DateInput('checkindate', true, 'DD-MON-YYYY')
</script>
<label for="Check-out-Date" class="required">Check-out Date:</label>
<script>
DateInput('checkoutdate', true, 'DD-MON-YYYY')
</script>
<label>
<div style="padding-top:10px;font-size:14px;color:white;">
<p>Total Charges: <span id="tot_charges">1995.00</span> THB
</p>
<p class="VAT"><span> Prices exclude VAT # 7%</span>
</p>
</div>
</label>
</fieldset>
<fieldset id="user-4">
<h2> </h2>
<label for="Comments" class="required">Comments :</label>
<textarea name="Comments"></textarea>
<div>
<label style="padding:0;">Please read our cancellation policy
</label>
<input type="checkbox" name="checkbox" id="checkbox" value="I agree to cancellation policy">
<label for="checkbox" id="agree" name="agree">I agree to cancellation policy</label>
</div>
<input type="submit" value="Submit" />
</fieldset>
</form>
<SCRIPT LANGUAGE="JavaScript">
function validate() {
var frm = document.forms["form"];
if (frm.checkbox.checked == false) {
alert("Please Agree To Our Cancellation Policy.");
return false;
} else return true;
}
</SCRIPT>
<script type="text/javascript">
var frmvalidator = new Validator("form");
frmvalidator.addValidation("Email", "maxlen=100");
frmvalidator.addValidation("Email", "req");
frmvalidator.addValidation("Email", "email");
frmvalidator.addValidation("Phone", "req");
frmvalidator.addValidation("Phone", "maxlen=100");
frmvalidator.addValidation("Phone", "numeric");
frmvalidator.setAddnlValidationFunction(validate);
</script>
Was trying to integrate something like this in :
function validateTheDate() {
var dateOK = false;
var Today = new Date();
if (Response_Requested_By_Object.picked.date < Today)
alert('Cannot select a date in the past.');
else if (Response_Requested_By_Object.picked.yearValue > 2020)
alert('Cannot select dates beyond 2020.');
else
dateOK = true;
return dateOK;
}
But not quite sure how to do it with existing validation there ?!?
This is how the validateDate function should look like:
function validateDate(){
var dateOK = false;
var today = new Date();
var startDt = new Date(document.getElementById("checkin").value).getTime();
var endDt = new Date(document.getElementById("checkout").value).getTime();
if (startDt < today || endDt < today)
alert('Cannot select a date in the past.');
else if (startDt > 2020 || endDt > 2020)
alert('Cannot select dates beyond 2020.');
else if(startDt > endDt){
alert ('Checkout date is greater than Checkin date.');
dateOK = true;
}
}
to add this custom function to you validator, just need to:
frmvalidator.setAddnlValidationFunction(validateDate);
Note: I'm sure there is a lot of (Javascript) Jquery plugins very good for validate forms and dates (using alert is not cool).

Categories