2

See the following jsFiddle link: http://jsfiddle.net/7gS6N/.

I'm trying to perform some simple field-level validation through knockout js.

Click "Add Error" to simulate adding an Error for the Name field.

When an error is added to the Errors collection, the css bindings fire, the expression evaluates to true and the css class is applied.

This is great, but how can I make my css binding expression property specific?

css: { error: Errors().length > 0 }

I only want the Name field to show the css class.

Thanks!

1
  • Have you considered using Knockoutjs validation plugin? It does what you are looking for github.com/ericmbarnard/Knockout-Validation Commented Jan 7, 2013 at 22:01

1 Answer 1

1

You need an extra observable, so instead of

self.Name = ko.observable("John")

you use

self.Name = new Field("John Smith");

where a Field has the following structure

function Field(value) {
  var self = this;
  self.value = ko.observable(value);
  self.hasError = ko.observable(false);
}

And your markup looks like

<div data-bind="with:Name">
  <input type="text" data-bind="value: value, css: { error: hasError }" />
</div>

This strategy is known as decorating an object; in this case I "wrapped" your variables in a class, but from there you can add label, errorMessage and other attributes you would want all those specific Fields to have. Finally, I updated your fiddle here with the working example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.