Knockout Validation - How to show error messages
Asked Answered
F

1

18

We're using Knockout.js and the Knockout-validation plugin. When a user returns to a page that has validation errors, we want the error messages to display. Does anyone know if it's possible to trigger knockout validation without actually changing the bound answer?

Fractionize answered 23/8, 2012 at 18:37 Comment(0)
F
48

The solution is to call showAllMessages. If the view model has nested observables, be sure to set ko.validation.configure to use deep grouping because the default value is false.

Example:

viewModel.save = function()
{
    var result = ko.validation.group(viewModel, {deep: true});
    if (!viewModel.isValid()) 
    {
        alert("Please fix all errors before preceding");
        result.showAllMessages(true);

        return false;
    }

    //actually save stuff, call ajax, submit form, etc
}

Alternatively, you can replace !viewModel.isValid() with result().length > 0

Fractionize answered 24/8, 2012 at 13:36 Comment(2)
Note that validatedObservable calls group behind the scenes and stores in errors property, so there is no need to do your own group. if (!viewModel.isValid()) { viewModel.errors.showAllMessages(); }Australasia
How to hide them back? I noticed that this made the appearance of errors dynamic, i.e. show/hide as errors are validated. What if I would like to go back to showing them all in a go, lets say on a push of a button, like this example here. ThanksNehru

© 2022 - 2024 — McMap. All rights reserved.