Can I manually add error messages in knockout-validation?
Asked Answered
P

2

10

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?

Pepi answered 19/9, 2012 at 8:33 Comment(2)
I asked the following question and got a good response #9129030Hards
Thanks - I d seen that before, I'm not exactly sure if its what I want, as I'm really trying to glue the knockout-validation pluggin to modelstate stuff that comes with mvc for free. I'll give it another read as I may have misunderstood?Pepi
W
16

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.

Warrant answered 26/5, 2013 at 17:50 Comment(0)
W
15

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);
Wealth answered 20/6, 2014 at 23:10 Comment(1)
This is useful. I think this is because errors don't display until the validation routine is triggered. Modifying the value or validating a group will trigger the validation and cause the previously set error to appear.Moule

© 2022 - 2024 — McMap. All rights reserved.