Jquery validate year not greater than today

2019-09-20 15:26发布

问题:

I'm trying to create a method for jquery validate plugin to validate if the year entered in a text field is not greater than today's year, but I can't tell why it is not working. Any help is much appreciated.

My script:

$.validator.addMethod("checkYear", function(value, element) {
  var year = $("#dateBirthYYYY").val();
  var myYear = new Date();
  myYear.setFullYear(year);
  var currentYear = new Date();
  currentYear.getFullYear();
  return currentYear > myYear;
}, "Invalid year");

回答1:

It should be much simplier:

$.validator.addMethod("checkYear", function(value, element) {
  var year = $("#dateBirthYYYY").val(); //why not $(element) ?!?
  return (new Date()).getFullYear() >= parseInt(year, 10);
}, "Invalid year");