Gaurav
Gaurav

Reputation: 8487

Wrong validation message is displaying by knockout?

I am using knokcout.js and knockout.validation plugin. I have an issue in my code with validation messages. I applied 2 validation on observable field (say password) like :

In Js Code

..
this.Password = ko.observable().extend({
       required: { message: "Enter password" },
       minLength: { params: 6, message: "Must be 6 chars long" }
});
.. 

In Html

<input type="password" data-bind="value: Password, valueUpdate:'afterkeypress"
  placeholder="Password" />

Now my problem is when i enter single character in the password filed than instead of showing validation message (Must be 6 chars long) it shows me message (Enter password) and than when i enter second character in the field than it shows me message (Must be 6 chars long). And this behavior is with all fields on which i applied validation. Can anybody please tell me where is the problem ?

Upvotes: 0

Views: 790

Answers (1)

jedatu
jedatu

Reputation: 4123

The code seems to be reacting to the 'keypress' rather than 'afterkeypress'. You are missing a single quote after 'afterkeypress' in your sample html.

The documentation doesn't really list 'afterkeypress' as an updateValue option, but it does seem work in my tests.

From documentation for value binding

If your binding also includes a parameter called valueUpdate, this defines additional browser events KO should use to detect changes besides the change event. The following string values are the most commonly useful choices:

  • "keyup" - updates your view model when the user releases a key
  • "keypress" - updates your view model when the user has typed a key. Unlike keyup, this updates repeatedly while the user holds a key down
  • "afterkeydown" - updates your view model as soon as the user begins typing a character. This works by catching the browser’s keydown event and handling the event asynchronously.

Of these options, "afterkeydown" is the best choice if you want to keep your view model updated in real-time.

The documenation recommends using the 'afterkeydown' choice for best results, and I found that to be the case.

I created a sample which uses 'keypress', 'afterkeypress' and 'afterkeydown'.

See: http://jsbin.com/anerop/3/edit (validatedObservable; Note: Click the "Run with js" button)

Binding to 'afterkeydown' seems to provide the best user experience. The 'afterkeypress' doesn't update until the control loses focus.

Sample data-bind:

<input type="password" data-bind="value: Password, valueUpdate:'afterkeydown'"
  placeholder="Password" />

I created another example which did not use validatedObservable and got similar results.

See: http://jsbin.com/itatic/1/edit (not validatedObservable; Note: Click the "Run with js" button)

Upvotes: 1

Related Questions