We help IT Professionals succeed at work.

Javascript date validation on onkeyUp using the leap year functionality

123 Views
1 Endorsement
Last Modified: 2019-01-14
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

Dorababu MTechnical Lead
CERTIFIED EXPERT
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
CERTIFIED EXPERT
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/
CERTIFIED EXPERT

Author

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

CERTIFIED EXPERT

Author

Commented:
and your function still returns false if i choose a seperate date from a select like 02/16/1960
CERTIFIED EXPERT

Author

Commented:
console.log(results); is always false
Zakaria AcharkiAnalyst Developer
CERTIFIED EXPERT
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/
CERTIFIED EXPERT

Author

Commented:
see this

http://prntscr.com/m72gq3

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

Commented:
Please tell me what you want to validate here, so I can adjust your code.
Zakaria AcharkiAnalyst Developer
CERTIFIED EXPERT
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

CERTIFIED EXPERT

Author

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
Analyst Developer
CERTIFIED EXPERT
Distinguished Expert 2018
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION
Zakaria AcharkiAnalyst Developer
CERTIFIED EXPERT
Distinguished Expert 2018

Commented:
Does this what you're looking for?
CERTIFIED EXPERT

Author

Commented:
looks like it, i am checking it, will post
Zakaria AcharkiAnalyst Developer
CERTIFIED EXPERT
Distinguished Expert 2018

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