2

I think this is a simple question. I'm using simple schema and I want to have a minDate and maxDate. The documentation talks about it in validation section but I'm not sure how to define it in the schema itself. Any help would be great. Thanks

Path: Schema.js

startDate: {
        type: Date,
        optional: true,
        autoform: {
            type: "bootstrap-datepicker"
          }
    },
    endDate: {
        type: Date,
        optional: true,
        autoform: {
            type: "bootstrap-datepicker"
          }
    }
bp123
  • 3,217
  • 8
  • 35
  • 74

1 Answers1

3

I found an issue in the simple-schema repo that goes over this. Here's how your code might look with a static min/max date:

startDate: {
    type: Date,
    optional: true,
    min: new Date(2016, 1, 1),
    autoform: {
        type: "bootstrap-datepicker"
    }
},
endDate: {
    type: Date,
    optional: true,
    max: new Date(2018, 1, 1),
    autoform: {
        type: "bootstrap-datepicker"
    }
}

You can use the custom validator if you want to make those dates dynamic. Here's a link to the relevant documentation. Your start date would look something like this:

startDate: {
    type: Date,
    optional: true,
    custom: function() {
        var myMinDate = new Date(); //today
        if(myMinDate > this.value) {
            return 'minDate';  //Error string according to the docs.
        } else {
            return true;
        }
    },
    autoform: {
        type: "bootstrap-datepicker"
    }
},
endDate: {
    type: Date,
    optional: true,
    custom: function() {
        var myMaxDate = new Date(2018, 11, 31); //Last day of 2018
        if(myMaxDate < this.value) {
            return 'maxDate';  //Error string according to the docs.
        } else {
            return true;
        }
    },
    autoform: {
        type: "bootstrap-datepicker"
    }
}
Stephen Woods
  • 4,049
  • 1
  • 16
  • 27
  • Thanks @Stephen. How do reference the endDate in the custom function? – bp123 Feb 05 '16 at 04:11
  • Sorry. What I meant was how do I reference the endDate that the user adds. As in if (startDate > endDate) { return 'minDate'; //Error string according to the docs. } else { return true; } – bp123 Feb 05 '16 at 04:23
  • Oh I see what you're saying. I just had to do that for my project actually - I did it client-side in my event. I just took the datepicker values and compared them. If startDate > endDate, I threw an error and didn't execute any server side logic. – Stephen Woods Feb 05 '16 at 04:25
  • Will that error if they don't have client side validation running, for instance they're using an old browser? – bp123 Feb 05 '16 at 04:28
  • No, you're not using jQuery validation in that case, you're using code to validate and inform the user on error. – Stephen Woods Feb 05 '16 at 04:44