Error Messaging Using KnockoutJS Observable Applying CSS

When doing error messages in an application I like to use KnockoutJS Observable to apply a css class to an input box to color it red meaning it’s required. The concept is quite simple really. You have an observable for the field.

self.FirstNameValidation = ko.observable('');

The point is when your validation fails, you add a message to the observable.

if(self.FirstName() == ''){
      self.FirstNameValidation('First Name Is Required');

So now that we have our observable set with an error message we can add a data-bind event to the input box to apply a css class to it.

<input id="firstName" data-bind="value: FirstName, css: { 'validationerror': FirstNameValidation() }">

Looking at the example above, the css class ‘validationerror’ will be added to the input box if there is a value in FirstNameValidation(). Simple way to add a visual cue to an input element that something is missing.

Leave a Reply

Your email address will not be published. Required fields are marked *

StackOverflow Profile