Search code examples
asp.net-mvc-3knockout.jsknockout-validation

Knockout Validation & Proper way to clear controls


I have the following code and it works fine, EXCEPT when you clear the property after you have inserted an item. The error shows up right away.

ko.validation.configure({
        insertMessages: false,
        decorateElement: true,
        errorElementClass: 'error'
    });

FirstName: ko.observable().extend({
            required: true
        }),

and I have add method in the knockout viewmodel

addItem: function () {
            if (!viewModel.isValid()) {
                viewModel.errors.showAllMessages();
                return false;
            } else {
                //DO SOMETHING
                this.SomeCollection.push(newInterviewee);
                this.FirstName(null);
                }
        },

I have the following in the HTML:

<div>
<label>First Name</label>
<input data-bind="value: FirstName, validationElement: FirstName, valueUpdate: 'keyup'" class="input" type="text">
</div>
<div>
<div>
<input data-bind="click: addItem" class="button" type="button">
</div>

The problem is that after I call this.FirstName(null). The error shows up right away! I want the error to show up only when they press the button even after the property is cleared


Solution

  • Here is the solution that is provided by Steve Greatrex: https://github.com/Knockout-Contrib/Knockout-Validation/issues/210