Reputation: 1212
How can I check that the date entered in a textbox is less than today's date using java script?
I m using code
var currentDate_Month = new Date().valueOf().getMonth();
var currentDate_Date = new Date().getDate();
var currentDate_Year = new Date().getFullYear();
var EnterDate_Month = new Date(document.getElementById('ctl00_ContentPlaceHolder1_txtDateReceived').value).getMonth();
var EnterDate_Date = new Date(document.getElementById('ctl00_ContentPlaceHolder1_txtDateReceived').value).getDate();
var EnterDate_Year = new Date(document.getElementById('ctl00_ContentPlaceHolder1_txtDateReceived').value).getFullYear();
if(EnterDate_Year<currentDate_Year) {
if(EnterDate_Month<currentDate_Month) {
if(EnterDate_Date<currentDate_Date) {
}
}
}
else {
str += '</br>* Date should be Less than or equals to current Date.';
return false;
}
But to my surprise the current date coming in the textbox control is Sat Jun 7 2014 when viewing it by -
new Date(document.getElementById('ctl00_ContentPlaceHolder1_txtDateReceived').value).toDateString();
Why is it returning the date in this format? (the date in text box is in format dd/mm/yyyy)
thanks in advance.
Upvotes: 0
Views: 25407
Reputation: 2627
A Date() can be initialized as
Date("mm/dd/yyyy")
Since this is the adopted method, the format of dd/mm/yyyy is not possible. The best method in your case will be to do the following
dateFields = (document.getElementById('ctl00_ContentPlaceHolder1_txtDateReceived').value.split('/')
date = Date(dateFields[2],dateFields[1]-1, dateFields[0])
This would be in the format
Date(year, month, date)
Then, you can compare the textbox date with the present date
date < Date.now()
Upvotes: 2
Reputation: 923
You could simplify your code:
var today = new Date();
var enterDate = new Date(Date.Parse(document.getElementById('ctl00_ContentPlaceHolder1_txtDateReceived')));
if (enterDate.valueOf() < today.valueOf())
{
// To what you have to do...
}
Upvotes: 2