Javascript date validation - year and full stops

Checking fields:

checkFields = function() {
  var colCheck = 0;
  var colArray = [];
  var colDupArray = [];
  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. Please amend!");
      return false;
    }

Validation:

isValidDate = function(day,month,year) {
  var dteDate;
  dteDate=new Date(year,month,day);

  var day = dteDate.getDate();
  var month = dteDate.getMonth() + 1;
  var year = dteDate.getFullYear();

  var formatted =
      (day < 10 ? "0" : "") + day + "/"  +
      (month < 10 ? "0" : "") + month + "/"  +
      year;

  return
+day === dteDate.getDate() && 
+month === dteDate.getMonth() &&
+year === dteDate.getFullYear();
}

The problem is that my code is accepting a date such as "03.06.2012" when I only want it to accept slashes between the numbers.

It also accepts "03/06/12" when I only want a four digit year.

Any ideas?

Answers


You somehow mixed a formatting with a validating function. This is how it should be:

function isValidDate(day,month,year) {
    var dteDate = new Date(year,month,day);

    return +day === dteDate.getDate()
        && +month === dteDate.getMonth()
        && +year === dteDate.getFullYear();
}
function formatDate(dteDate) {
    var day = dteDate.getDate(),
        month = dteDate.getMonth() + 1,
        year = dteDate.getFullYear();

    var formatted = (day < 10 ? "0" : "") + day + "/"
                  + (month < 10 ? "0" : "") + month + "/"
                  + year;
    return formatted;
}

As suggested this let's the user enter a date in a format of choice. The output should be as expected for you.

I've expanded my little demo with a Date.prototype.formatDateField and a library called moment which also seems to be pretty clean. As third option the jQuery-UI $.datepicker.formatDate()

Still this isn't bulletproof and maybe you should look for a datepicker which can handle the format for you. The best solution to your problem imho.

If you want to go custom however this might get you started:

// prototype
Date.prototype.formatDateField = function (options) {
    var i = 0,
        date = [],
        len = date.push(this.getDate(), this.getMonth() + 1, this.getFullYear());

    for (; i < len; i += 1) {
        var chunk = date[i];
        date[i] = chunk < 10 ? options.pad + chunk : chunk;
    }

    return date.join(options.separator);
};

// Setup output
var cfg = {
    fieldDate: "#fieldDate",
    options: {
        pad: "0",
        format: "dd/MM/yyyy",
        separator: "/"
    }
};

// function to call
function reformatInput(){
    $(cfg.date).blur(function(){
        var moment = moment(this.value).calendar(cfg.options2.format),
            prot = new Date(this.value).formatDateField(cfg.options2),
            jqueryui = $.datepicker.formatDate(cfg.options2.format, new Date(this.value));

        $(cfg.fieldDate1).val(moment);
        $(cfg.fieldDate2).val(prot);
        $(cfg.fieldDate3).val(jqueryui);
    });
}

// run on demand
reformatInput();

demo: http://jsfiddle.net/tive/YvdKA/


At least for the four-digit-year problem, look at this jfiddle output and the code:

d1 = new Date(1,2,3);
d2 = d1.getFullYear();
d3 = d1.getMonth();
d4 = d1.getDay();
alert(d2);
alert(d3);
alert(d4);

The Date constructor is not strict about four year digits (despite what Mozilla says you should do). In the example above, it's even taking the int 1 as a year! That is reflecting in your program accepting years that aren't 4 characters in length.

Perhaps test the length of the year string?

As for the split, perhaps you can use a regular expression that would both split and make sure that you're only accepting slashes (as suggested here)?


Need Your Help

Correct way to bind parameters using MySQL “IN” syntax in Yii2?

php mysql yii yii2

Ok, I'm using Yii2 and I'm familiar with preparing/binding data when using mysql queries, such as:

Calculated Collection Mapping

jpa jpa-2.0 eclipselink jpa-2.1

Is it possible with Eclipselink (or even better with standard JPA 2.x) to use JPQL or SQL to define a calculated collection mapping?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.