1

I'm using the jQuery Validate plugin and wanted to know how can I validate that a given date is in the current year?

I have this code that make sure the field is required and that it is a valid date, but I want to also make sure the date is in the current year, current being 2017

// orders dates fields are required and must be in current year

$(".order-dates").each(function (item) {
    $(this).rules("add", {
        required: true,
        date: true
    });
});
4
  • you don't need the .each() at all I think. .rules should operate over a collection - since it's a plugin. It's absolutely strange item is left secret from us... "I want to also make sure the date is in the current year, current being 2017" ... what date? Commented Oct 26, 2017 at 19:27
  • Possible duplicate of stackoverflow.com/questions/28090401/… Commented Oct 26, 2017 at 19:31
  • I'm using a class for the field names, so the each() loop is to iterate over all fields with that class. The fields I'm iterating over have date values in them. They could be any date value as they are used entered. "Item" is the date value and $(this) represents the field element! Commented Oct 26, 2017 at 19:47
  • @RokoC.Buljan, the .each() is absolutely required here since this plugin's methods can only be attached to a single element, not a collection. Commented Oct 28, 2017 at 18:32

1 Answer 1

3

You'll have to create a custom method to jquery-validator and use this in your validation rules

This is what your custom method will be (I am assuming you've added a class class="date" in your field)

<script type="text/javascript">
    $(document).ready(function() {
    $.validator.addMethod("ifDateInCurrentYear", function(value, element) {
        var date= $('.date').val();
   if(Date.parse(date).getFullYear() - new Date().getFullYear() == 0)
      return true;
   else return false;
    }, "* Date is not valid");

});
</script>

You can use this like

$(".order-dates").each(function (item) {
$(this).rules("add", {
    required: true,
    date: true,
    ifDateInCurrentYear : true;
});
});
Sign up to request clarification or add additional context in comments.

Comments

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.