Search code examples
knockout.jsknockout-validation

Knockout-Validation - Date greater than another date


I've been looking at the different methods of using knockout-validation to compare dates. I can't get it to work with my obervables in a validatedObservable object.

I need the validatedObservable for checking if the validation passed/ failed on the button click - it's my grouping of controls.

Here's my demo:

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/knockout-2.3.0.js"></script>
<script src="~/Scripts/knockout.validation.min.js"></script>
<script src="~/Scripts/moment.min.js"></script>
<form>
    <table>
        <tr>
            <td>Name:</td>
            <td><input type="text" data-bind="value:contactForm().name" value="" /></td>
        </tr>
        <tr>
            <td>From:</td>
            <td><input type="text" data-bind="value:contactForm().fromDate" value="" /></td>
        </tr>
        <tr>
            <td>To:</td>
            <td><input type="text" data-bind="value:contactForm().toDate" /></td>
        </tr>
    </table>
    <button type="button" data-bind='click: submit'>Submit</button>
</form>
<script>

    ko.validation.init({
        messagesOnModified: false,
        parseInputAttributes: true,
        grouping: {
            deep: true
        }
    });

    var myViewModel = function () {
        var self = this;
        self.contactForm = ko.validatedObservable({
                name :ko.observable().extend({ required: true }),
                fromDate :ko.observable('2014-11-10').extend({ date: true }),
                toDate: ko.observable('2014-11-10').extend({date: true, min: this.fromDate })
            });
            submit = function () {
                console.log(this.contactForm.isValid())
            };
        };

        ko.applyBindings(new myViewModel());

</script>

I basically can't get the this line working:

toDate: ko.observable('2014-11-10').extend({date: true, min: this.fromDate })

anyone any ideas?


Solution

  • That's because you're using this in an object literal creation (when you refer to fromDate in toDate declration), and upon constructing that object, this is still referring to the encapsulating function context (myViewModel in this case).

    Try this instead (based on this answer):

    self.contactForm = ko.validatedObservable({
                name: ko.observable().extend({ required: true }),
                fromDate: ko.observable('2014-11-10').extend({ date: true }),
                toDate: ko.observable('2014-11-10'),
                init: function() {
                    this.toDate = this.toDate.extend({date: true, min: this.fromDate});
                    return this;
                }
            }.init());