JavaScript Date of birth under 18 - javascript

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.

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>

how to update the form field automatically

I am developing a task management system in that i am having the age field in registration form i am having doubt about how to update the field automatically when i click.
my script is
<script>
var a = document.age1.dob.value;
age = a.getFullYear();
var curr = new Date();
year = curr.getFullYear();
var age1 = year - age;
</script>
i calculated the age and stored it in age1 variable.
<form id="form2" action="#" method="post" name="age1">
<h4><b>Register here</b></h4>
<b>Name</b>: <input type="text" name="name" required="required" placeholder="Your name" pattern="[a-zA-Z0-9\s]+"><br><br>
<b>E-mail</b>: <input type="email" name="email" required="required" placeholder="someone#example.com" pattern="[a-z0-9._+%-]+#[a-z0-9.-]+\.[a-z]{2,4}$"><br><br>
<b>Password</b>: <input type="password" name="password" required="required"><br><br>
<b>DOB</b>: <input type="text" name="dob" required placeholder="dd/mm/yyyy" pattern="^[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2}$"><br><br>
<b>Age</b>: <input type="text" name="age" id="age2"><br><br>
<b>Address</b>: <textarea name="address" rows="6" cols="30"></textarea>
<button id="butr" type="submit" class="btn btn-warning">Signup</button>
After i input my DOB in the registration form and click the age field i want the calculated age that i stored it in age1 variable to automatically update the value in age field that i have it in my registration form
Add an onchange function to dob field
<input type="text" onchange="ageCalculation()" name="dob">
Add this code in your <script>
function ageCalculation(){
if(document.age1.dob.value!==""){
var a = document.age1.dob.value;
a=new Date(a);
age = a.getFullYear();
var curr = new Date();
year = curr.getFullYear();
var age1 = year - age;
document.age1.age.value=age1;
}
}

JavaScript validating datetime-local from form

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.

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