Reputation: 303
I'm new to javascript. I'm trying to create a page that has an input option for date of birth. Once the submit button is clicked, I want to verify that the person is not underage (above 18).
This is my HTML code
<form id="myForm" method="get" action="#">
<p>Date of birth: <input type="date" name="dob" value="MM-DD-YYYY" required></p>
<p><input type="submit" value="submit" onclick="return validate_date_of_birth()">
</form>
and this is my javascript function:
function validate_date_of_birth(){
var dob = document.forms["myForm"]["dob"].value;
var ageDifMs = Date.now() - dob.getTime();
return true;
}
I'm getting a problem with dob.getTime(). Note that I'm not really verifying the age in the above code. That would require an if loop to verify the age. I'm stuck at a point where the difference is not being calculated. I tried to check the values of Date.now() and dob.getTime() by using the alert() function in javascript. For dob.getTime(), the value it prints out is "undefined". What am I doing wrong?
Upvotes: 2
Views: 1590
Reputation: 9937
You used getTime()
on the input value, but you need to use it on a Date
object. For this, construct a Date
object from the input value, and then you'll be able to get the time on it. Be careful though, Date
needs to be in one of these formats :
YYYY-MM-DD
MM/DD/YYYY
otherwise you'll get an error. You can obviously receive any format and then reformat it to what you need though.
function validate_date_of_birth(){
var dob = document.forms["myForm"]["dob"].value;
var ageDifMs = Date.now() - new Date(dob).getTime(); // we make a new Date object from dob
console.log(ageDifMs);
return false; // so we can see the result and not be redirected
}
<form id="myForm" method="get" action="">
<p>Date of birth: <input type="date" name="dob" value="YYYY-MM-DD" required></p>
<p><input type="submit" value="submit" onclick="return validate_date_of_birth()">
</form>
Upvotes: 0
Reputation: 2290
.getTime()
is a method of Date/Time object
in JavaScript.
var dob = document.forms["myForm"]["dob"].value;
is not a valid Date
object as this is a string.
which caused you an error in dob.getTime()
.
to prevent the error simply parse dob
to Date first after setting it.
var dob = new Date(document.forms["myForm"]["dob"].value);
OR
var dob = document.forms["myForm"]["dob"].value;
dob = new Date(dob);
hope that helps
Upvotes: 1