Ionut Ionut - 1 month ago 23
Javascript Question

How to prevent future year in dateTime validation?

I've made a custom date and time validation for an input using jQuery validate plugin and maskedInput plugin.

Is there a way to make in that custom validation, a validation to prevent entering a year bigger than current year?

My code:



$("#date").mask("99/99/9999 99:99", {
placeholder: "mm/dd/yyyy hh:mm"
});
$.validator.addMethod("dateTime", function(value, element) {
var stamp = value.split(" ");
var validDate = !/Invalid|NaN/.test(new Date(stamp[0]).toString());
var validTime = /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i.test(stamp[1]);
return this.optional(element) || (validDate && validTime);
}, "Invalid datetime.");

$('#form').validate({
rules: {
date: {
required: true,
dateTime: true
}
},
messages: {
date: {
required: ""
}
}
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>

<form action='' method='post' id='form'>
<input type='text' name='date' value='' id='date' placeholder='mm/dd/yyyy hh:mm'>
</form>




Answer

add a new method for checking the year

jQuery.validator.addMethod("minYear", function (value, element) {
    var year = new Date(value).getFullYear();
    var curentYear = new Date().getFullYear();
    return this.optional(element) || year <= curentYear;
}, 'Year can not be greater than current year');

add the same in the validate rules

$('#form').validate({
  rules: {
    date: {
      required: true,
      dateTime: true,
      minYear: true
    }
  },
  messages: {
    date: {
      required: ""
    }
  }
})