validation for yyyymmdd
HI,
i am entering date in the format 'yyyymmdd' in the form.
once i click save button , it must validate the date .
any validation code ,please.
Thanks & Regards,
drams.
with Date object:
Code:
<script type="text/javascript">
function isValidDate(year, month, date)
{
var flagDate = new Date(year, month, date);
if (year != flagDate.getFullYear() || month != flagDate.getMonth() || date != flagDate.getDate())
{
return false;
}
return true;
}
alert(isValidDate(2000, 1, 29));
alert(isValidDate(2001, 1, 28));
alert(isValidDate(2001, 1, 29));
alert(isValidDate(2007, 12, 1));
</script>
Without Date object:
Code:
<script type="text/javascript">
function getDayInMonth(year, month)
{
if (month == 2)
{
if (year % 4 == 0 && (year <= 1582 || (year % 100 != 0 || year % 400 == 0)))
{
return 29;
}
return 28;
}
if (month > 7) month ++;
return (month % 2 == 0) ? 30 : 31;
}
function isValidDate(year, month, date)
{
for (i = 0; i < arguments.length; i++)
{
if (isNaN(arguments[i]) || arguments[i] < 1) return false;
}
if (month > 12 || date > getDayInMonth(year, month)) return false;
return true;
}
alert(isValidDate(2000, 2, 29));
alert(isValidDate(2001, 4, 31));
alert(isValidDate(2100, 2, 29));
alert(isValidDate(1500, 2, 29));
</script>
forty2, there's one problem with your logic, javascript month in Date Object goes from 0(Jan)-11(Dec) extremely stupid i know, so it should be:
(also added parseInt for protection)
<script type="text/javascript">
function isValidDate(year, month, date)
{
var flagDate = new Date(parseInt(year, 10), parseInt(month, 10) - 1, parseInt(date, 10));
if (year != flagDate.getFullYear() || month != flagDate.getMonth()+1 || date != flagDate.getDate())
{
return false;
}
return true;
}
alert(isValidDate(2000, 1, 29));
alert(isValidDate(2001, 1, 28));
alert(isValidDate(2001, 1, 29));
alert(isValidDate(2007, 12, 1));
</script>
PS: You should edit your post because this is thread is the one that pops out first in a google search
Thread Information
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Bookmarks