0

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?

4
  • Why not use your formatter to render a valid date to your textfield? You are trying to validate a text field against your format. stackoverflow.com/questions/3605214/… Commented May 1, 2013 at 14:47
  • see stackoverflow.com/questions/51224/… for inspiration too Commented May 1, 2013 at 15:04
  • Your isValid function is completely messed up. Is that only a c&p error or the actual code you're using? It will never return true. Commented May 1, 2013 at 15:07
  • Can you add HTML As well? Commented May 1, 2013 at 15:21

3 Answers 3

2

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/

Sign up to request clarification or add additional context in comments.

1 Comment

+1 on moment.js. it can be glorious once you get the hang of it. (its website is also pretty remarkable.)
1

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;
}

Comments

1

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)?

3 Comments

thanks @Bergi! my bad with the original ordering of the parameters.
But you're still entering a 13th month? That's the reason why it alerts 14, btw.
Thanks @Bergi! I've simplified it and clarified in the response, since the point is that the constructor isn't strict about the year it takes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.