Juan José Cumba
Juan José Cumba

Reputation: 97

Validating with knockout-validation

Working with knockout.js (and knockout-validation) I have this:

self.nickname = ko.observable("").extend({
    required: true,
    minLength: 3
});

and

<input type="text" data-bind="value: nickname" class="short" maxlength="30" />
<div class="formRow rowErrorMsg" data-bind="visible: nickname.isValid() == false"><span class="staticImages staticImagesError"></span> <?php text("Enter a valid username") ?></div>

but the problem is that when "nickname" its not valid then apper a text next to the input control. The DIV with the error message start visible and then work fine.

I need to do this:

  1. when "nickname" is not valid then just display the DIV with my custom message and format.
  2. when page is loaded then the DIV have to stay hidden.

Upvotes: 1

Views: 7930

Answers (1)

delixfe
delixfe

Reputation: 2491

You need to configure knockout-validation to not show the error-messages. There are two ways.

The first is via binding:

<div data-bind='validationOptions: { insertMessages: false }'>
    <input type="text" data-bind="value: nickname" class="short" maxlength="30" />
    <div class="formRow rowErrorMsg" data-bind="visible: nickname.isValid() == false">
</div>

The second one is via code:

  • Use the ko.validation.init({ insertMessages: false }); function
  • Use the ko.applyBindingsWithValidation(viewModel, rootNode, { insertMessages: false }); function **contextual

A description of all configuration options can be found at: https://github.com/ericmbarnard/Knockout-Validation/wiki/Configuration

If you have many fields you have to validate you could use an messageTemplate template instead of manually creating all the errorMessage divs.

Upvotes: 11

Related Questions