Reputation: 340
I have a form element of date type:
<input type="date" class="form-control" name="InputDOB" id="DOB"
placeholder="DOB" onblur="dateValidate()" required>
The JavaScript code is here:
function dateValidate(){
var date=new Date();
var pass1 = document.getElementById("DOB");
alert(pass1.value);
var date = new Date();
today=date.getFullYear()+'-'+(date.getMonth() + 1)+'-'+date.getDate();
if(pass1.value<today){
alert("date is correct ");
}
}
Upvotes: 1
Views: 134
Reputation: 7117
you need to use getTime();
to compare two dates like
function dateValidate(){
var input = document.getElementById("DOB");
alert(input.value);
var inputDate = new Date(input.value).getTime();
var today = new Date().getTime();
if(inputDate<today){
alert("date is correct");
}
}
Upvotes: 0
Reputation: 157
Based on the code that you've posted, this is how you do it :
html:
<input type="date" class="form-control" name="InputDOB" id="DOB" placeholder="DOB" required>
application.js file that you should load into your HTML file and I'm also using JQuery to accomplish this so you should load it too.
$(document).ready(function () {
$("#DOB").on("blur", function () {
var date=new Date();
var pass1 = document.getElementById("DOB");
alert(pass1.value);
today=date.getFullYear()+'-'+(date.getMonth() + 1)+'-'+date.getDate();
alert(today);
if(pass1.value<today){
alert("date is correct ");
}
})
});
DEMO:
http://fiddle.jshell.net/a2fjzqzw/
Upvotes: 1
Reputation: 8488
You don't need today
, just change your if
to
if(new Date(pass1.value)< date){
alert("date is correct ");
}
//OR
if(new Date(pass1.value)< new Date()){
alert("date is correct ");
}
Upvotes: 1
Reputation: 2181
I always use moment.js
with JavaScript when messing with dates. It mitigates most if not all the hardship when manipulating dates in JavaScript and is a brilliant library.
http://momentjs.com/docs/#/displaying/difference/
The difference method may get you where you need, if not I'm sure you can find a solution in the API.
Upvotes: 0