Javascript date validation on onkeyUp using the leap year functionality

Gurpreet Singh Randhawa
Gurpreet Singh Randhawa used Ask the Experts™
on
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
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Dorababu MSenior Software Engineer
Distinguished Expert 2018

Commented:
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 Developer
Distinguished Expert 2018

Commented:
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/
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

Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

and your function still returns false if i choose a seperate date from a select like 02/16/1960
console.log(results); is always false
Zakaria AcharkiAnalyst Developer
Distinguished Expert 2018

Commented:
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/
see this

http://prntscr.com/m72gq3

still giving invalid results, if i keep on changing the date
Zakaria AcharkiAnalyst Developer
Distinguished Expert 2018

Commented:
Please tell me what you want to validate here, so I can adjust your code.
Zakaria AcharkiAnalyst Developer
Distinguished Expert 2018

Commented:
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

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
Analyst Developer
Distinguished Expert 2018
Commented:
You're welcome,

Check this updated fiddle :

https://jsfiddle.net/z_acharki/doukv5cf/
Zakaria AcharkiAnalyst Developer
Distinguished Expert 2018

Commented:
Does this what you're looking for?
looks like it, i am checking it, will post
Zakaria AcharkiAnalyst Developer
Distinguished Expert 2018

Commented:
Ok take your time, if you need any adjustment let me know.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial