Reputation: 11480
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>
Upvotes: 0
Views: 616
Reputation: 13699
You can create your own method using addMethod
like this:
jQuery.validator.addMethod("minDate", function (value, element) {
var now = new Date().getFullYear();
var myDate = new Date(value).getFullYear();
return this.optional(element) || myDate < now;
});
$('#form').validate({
rules: {
date: {
required: true,
dateTime: true,
minDate: true
}
},
messages: {
date: {
minDate: "The date(year) must not be in the future"
}
}
})
Hope this helps!
Upvotes: 1
Reputation: 57095
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: ""
}
}
})
Upvotes: 1