Alias
Alias

Reputation: 413

Javascript date validation allowing wrong characters

For some reason, my date validation allows fullstops to be passed, but only at the end of that part of the date, e.g. 12./10/201 gets passed but 1.2/10/201 doesn't.

Here is my code:

var iDate = $("check_date").value;

  if(iDate.length > 0) {
    var a = iDate.split("/"); 
    if(isValidDate(a[0],a[1]-1,a[2]) == false){
      alert("You have entered an invalid date.");
      return false;
    }

isValidDate = function(day,month,year) {
  var dteDate;
  dteDate=new Date(year,month,day);
  return ((day==dteDate.getDate()) && (month==dteDate.getMonth()) && (year==dteDate.getFullYear()));
}

Any ideas?

Upvotes: 0

Views: 359

Answers (5)

Anup Paudel
Anup Paudel

Reputation: 1

This is my version of date validation. It will not allow to enter wrong date even some one intend to type. This will also auto populate / after month and day.

$("#date").keyup(function (e) {
                // validation for length max 10
                var temp = $(this).val();
                if (temp.length > 10) $(this).val(temp.substring(0, temp.length - 1));

                var key = String.fromCharCode(e.keyCode);
                console.log(key + " " + e.keyCode);
                var regex = /[0-9]|[a-i]|\/|\`|\o|\¿|\%|\'|\$/;                            
                // checking teh allowed character
                if (!regex.test(key)) {
                    // checking backspace and shift key ( need to allow)
                    if (e.keyCode != 8 && e.keyCode != 16) {
                        var tam = $(this).val().length;
                        $(this).val(temp.substring(0, tam - 1));
                    }
                }
                else {
                    //if its not backslash
                    if (e.keyCode != 191 && e.keyCode != 111) {
                        if ($(this).val().length == 2) {
                            $(this).val($(this).val() + "/");
                        } else if ($(this).val().length == 5) {
                            $(this).val($(this).val() + "/");
                        }
                    }
                    else {
                        // if backslash
                        if ($(this).val().length != 3 && $(this).val().length != 6) {
                            var tam = $(this).val().length;
                            $(this).val(temp.substring(0, tam - 1));
                        }
                    }
                }
            });

Upvotes: 0

J-man Venk
J-man Venk

Reputation: 53

  1. is valid number. After it is passed to the Date constructor it translated to Number as 12.0 and it obviously equals to 12. 1.2 is not. I'd recommend you to match the regexp first and then check the correctness of the parts as you did.

I would suggest you to implement something like this:

function isValidDate(dateString)
{
    if(! dateString.match(/((1[0-2])|(0?\d))\/(([0-2]?\d)|(3[0-1]))/(\d\d)?\d\d/) )
        return false;

    var parts = dateString.split("/");
    var dateToCheck = new Date(parts[0],parts[1]-1,parts[2]);

    return ((parts[0]==dateToCheck.getDate()) && (parts[1]==dateToCheck.getMonth()+1) && (parts[2]==dateToCheck.getFullYear()));
}

Upvotes: 0

Cerbrus
Cerbrus

Reputation: 72947

This is because "12." is interpreted as 12, when parsing the string to a number (This happens internally, in the date object).
Try this:

if(isValidDate(a[0],a[1]-1,a[2]) == false && iDate.indexOf('.') == -1){

Basically, just check for the dot.

Upvotes: 0

jValdron
jValdron

Reputation: 3418

As discussed in the comments, here is the solution:

isValidDate = function(day,month,year) {
    var dteDate;
    dteDate=new Date(year,month,day);
    return ((day.toString()===dteDate.getDate().toString()) && (month.toString()===dteDate.getMonth().toString()) && (year.toString()===dteDate.getFullYear().toString()));
}

You also need the toString() methods, as if you compare "12" and 12, it won't be equal. Now you'll compare "12" with "12" which will be equal for valid dates.

Upvotes: 1

Felipe Oriani
Felipe Oriani

Reputation: 38638

You can use a function to check if the date is valid. Take a look at this code:

function isDate(dateStr) {
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

    if (matchArray == null) {
        alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
        return false;
    }

    month = matchArray[1]; // p@rse date into variables
    day = matchArray[3];
    year = matchArray[5];

    if (month < 1 || month > 12) { // check month range
        alert("Month must be between 1 and 12.");
        return false;
    }

    if (day < 1 || day > 31) {
        alert("Day must be between 1 and 31.");
        return false;
    }

    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
        alert("Month "+month+" doesn`t have 31 days!")
        return false;
    }

    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day==29 && !isleap)) {
            alert("February " + year + " doesn`t have " + day + " days!");
            return false;
        }
    }
    return true; // date is valid
}

Upvotes: 2

Related Questions