1
votes


I try to use KnockoutJs validation plugin and I have a problem. Before post data from input I validate the value, if it is correct I post it and reset my viewmodel to the default state, if value isn't correct I wrap the input into the red border by adding some css class (or add error message). The problem is that this works only once: after post data I reset my viewmodel to the default state (as I said before), the input field becomes empty and if I try to post this empty data, validation works, but css class doesn't apply (error message doesn't appear). Please try my Fiddle example, what's wrong ?

* [Update].

So, I found workaround: just add additional code to data-bind attribute

validationElement: itemToAdd().Name

it should be

<input data-bind='value: itemToAdd().Name, validationElement: itemToAdd().Name' />

It works, but looks bad. Anyway, it will be good, if someone can fix my previous code.

2

2 Answers

0
votes

Just change

var t = ko.validation.group(viewModel.itemToAdd())

to

var t = ko.validation.group(viewModel.itemToAdd)
0
votes

I've put together a fiddle exemplifying my answer.

One way to approach this is to have your activeAccount object have a property, I called mine errors, that would hold all the validation messages for that object.

var activeAccount = function(data) {
    this.Id = ko.observable(data.id);
    this.Name = ko.observable(data.name).extend({ required: { message: 'Enter account name.'} });
    this.UserId = ko.observable(1);
    this.errors = ko.validation.group(this);
};

var viewModel = {
    items: ko.observableArray([]), 
    itemToAdd: ko.observable(new activeAccount({})),
    createItem: function (item) {
        if (item.errors().length == 0) {
            viewModel.items.push(item);
            viewModel.itemToAdd(new activeAccount({}));
        } else {
            item.errors.showAllMessages();
        }
    }
};

Once you've saved the item (whether it's posting to the server, pushing to an observableArray or both) you then "reset" itemToAdd by setting it to a new activeAccount({}) by passing an empty object to the constructor.