Avatar of Coast Line
Coast Line
Flag for Canada asked on

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
JavaScriptjQuery

Avatar of undefined
Last Comment
Zakaria Acharki

8/22/2022 - Mon
Dorababu M

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 Acharki

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/
Coast Line

ASKER
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

This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Coast Line

ASKER
and your function still returns false if i choose a seperate date from a select like 02/16/1960
Coast Line

ASKER
console.log(results); is always false
Zakaria Acharki

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/
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Coast Line

ASKER
see this

http://prntscr.com/m72gq3

still giving invalid results, if i keep on changing the date
Zakaria Acharki

Please tell me what you want to validate here, so I can adjust your code.
Zakaria Acharki

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

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Coast Line

ASKER
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
ASKER CERTIFIED SOLUTION
Zakaria Acharki

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Zakaria Acharki

Does this what you're looking for?
Coast Line

ASKER
looks like it, i am checking it, will post
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Zakaria Acharki

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