Javascript date validation on onkeyUp using the leap year functionality

I have this piece of code where i am trying to validate the jquery based Date of Birth Validation.

is there any JS function which also checks the full date if it falls in a leap year or not, i am trying this but it does seems to be working

function isValidDate(s) {
  var bits = s.split('/');
  var d = new Date(bits[2] + '/' + bits[1] + '/' + bits[0]);
  return !!(d && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[0]));
}

Open in new window


date i tested is: 02/29/1920 - it is giving false (edited)

testing it like this:

    function init_inputOnKeyUp(){
        $('select[name="day"],select[name="year"]').off('change');
        $('select[name="month"],select[name="day"],select[name="year"]').on('change', function(e) {
        if (type == 'select') {
            var newdate = $('select[name="month"]').val() + '/' + $('select[name="day"]').val() + '/' + $('select[name="year"]').val();
                        var results = isValidDate(newdate.toString());
                        console.log(results);
                        console.log(newdate.toString());
        }
        });
}

Open in new window


problem i can't use any extra library like moment.js

the error is it is always giving me false when i try to validate with a full date

i am not sure at this point, if the error is happening on leap year or onchange issue
LVL 16
Gurpreet Singh RandhawaCEOAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dorababu MSenior Software EngineerCommented:
This will give you whether the year is leap year or not

function leapYear(year)
{
  return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}

Open in new window

Zakaria AcharkiAnalyst DeveloperCommented:
Hi Gurpreet,

Here is an article checks whether a given year is a leap year in the Gregorian calendar with detailed explanation :

https://www.w3resource.com/javascript-exercises/javascript-basic-exercise-6.php

But the main problem in your code is in the undefined variable type, instead you could use the is() function to check the current element node name like :

if ($(this).is('select')) {

Open in new window


Working Sample

Using the leap year function, the validation will return true just when the year is a leap, something like :

https://jsfiddle.net/z_acharki/s05kj6zw/
Gurpreet Singh RandhawaCEOAuthor Commented:
this function should return me true if good, it is returning "undefined"

function isValidDate(sDate) {
    var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
    if (sDate.match(dateformat)) {
        var seperator1 = sDate.split('/');
        var seperator2 = sDate.split('-');

        if (seperator1.length > 1) {
            var splitdate = sDate.split('/');
        } else if (seperator2.length > 1) {
            var splitdate = sDate.split('-');
        }
        var dd = parseInt(splitdate[0]);
        var mm = parseInt(splitdate[1]);
        var yy = parseInt(splitdate[2]);
        var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        if (mm == 1 || mm > 2) {
            if (dd > ListofDays[mm - 1]) {
                return false;
            }
        }
        if (mm == 2) {
            var lyear = false;
            if ((!(yy % 4) && yy % 100) || !(yy % 400)) {
                lyear = true;
            }
            if ((lyear == false) && (dd >= 29)) {
                return false;
            }
            if ((lyear == true) && (dd > 29)) {
                return false;
            }
        }
    } else {
        return false;
    }
}

Open in new window

Price Your IT Services for Profit

Managed service contracts are great - when they're making you money. Yes, you’re getting paid monthly, but is it actually profitable? Learn to calculate your hourly overhead burden so you can master your IT services pricing strategy.

Gurpreet Singh RandhawaCEOAuthor Commented:
and your function still returns false if i choose a seperate date from a select like 02/16/1960
Gurpreet Singh RandhawaCEOAuthor Commented:
console.log(results); is always false
Zakaria AcharkiAnalyst DeveloperCommented:
I have adjusted your code a little bit, but the main issue was that you're not returning true in the valid date case so I have added `return true;` to your code.

https://jsfiddle.net/z_acharki/smoxpwg9/
Gurpreet Singh RandhawaCEOAuthor Commented:
see this

http://prntscr.com/m72gq3

still giving invalid results, if i keep on changing the date
Zakaria AcharkiAnalyst DeveloperCommented:
Please tell me what you want to validate here, so I can adjust your code.
Zakaria AcharkiAnalyst DeveloperCommented:
I think your main problem comes from here :

var dd = parseInt(splitdate[0]);
var mm = parseInt(splitdate[1]);
var yy = parseInt(splitdate[2]);

Open in new window


You're setting the value of the month in dd and the value of day in mm should be :

var mm = parseInt(splitdate[0]);
var dd = parseInt(splitdate[1]);
var yy = parseInt(splitdate[2]);

Open in new window


According to the order you sets here :

var newdate = $('select[name="month"]').val() + '/' + $('select[name="day"]').val() + '/' + $('select[name="year"]').val();

Open in new window

Gurpreet Singh RandhawaCEOAuthor Commented:
that might be the problem, i am not sure completely sure, but this is not validating properly, please make it work, if the change is required, please do

Thanks
Zakaria AcharkiAnalyst DeveloperCommented:
You're welcome,

Check this updated fiddle :

https://jsfiddle.net/z_acharki/doukv5cf/

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Zakaria AcharkiAnalyst DeveloperCommented:
Does this what you're looking for?
Gurpreet Singh RandhawaCEOAuthor Commented:
looks like it, i am checking it, will post
Zakaria AcharkiAnalyst DeveloperCommented:
Ok take your time, if you need any adjustment let me know.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.