Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I manually add error messages in knockout-validation?

I'm using knockout.js and knockout-validation with MVC 4. I can perform client side validation fine with knockout-validation. However I need to ensure that any viewmodels posted to my controller are valid. Therefore I manually validate my view models server side and return the modelstate serialized as JSON (a co-worker wrote a simple function to do this). My problem is that I'd like to some how use knockout-validation to consume the JSON serialised modelstate to output errors.

So is there any way to manually add errors and messages in knockout-validation?

like image 496
bplus Avatar asked Sep 19 '12 08:09

bplus


2 Answers

In addition to what Kevin said I found I needed to call isModified to make the message actually show. I think this is because I changed some default settings for when messages appear.

observable.setError('Your password is incorrect');
observable.isModified(true);
like image 189
Simon_Weaver Avatar answered Sep 28 '22 01:09

Simon_Weaver


The latest knockout-validation version has the following added to it:

//manually set error state
observable.setError = function (error) {
    observable.error = error;
    observable.__valid__(false);
};

//manually clear error state
observable.clearError = function () {
    observable.error = null;
    observable.__valid__(true);
}

so you can use those to manually add errors to your observables, but like the other question that graeme linked had asnwered, there is no built in way to map them.

What i've done before is just display model state errors below/above the forms to show server side validation errors, and have ko validation handle all the client side, next to the input type errors. much easier than coming up with a complex mapping scheme, especially if you have complex form data.

like image 29
Kevin Nacios Avatar answered Sep 28 '22 00:09

Kevin Nacios