Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  77] [ 4]  / answers: 1 / hits: 8695  / 10 Years ago, fri, may 2, 2014, 12:00:00

When binding values to a drop down list and using knockout validation, the error message seems to always display even if my knockout validation settings say messagesOnModified: true.



HTML



<input type=text data-bind=value: Name />
<br />
<select data-bind=value: State>
<option value=>Select a state...</option>
<option value=NY>New York</option>
<option value=NJ>New Jersey</option>
</select>


JS



var ViewModel = function () {
var self = this;

self.Name = ko.observable().extend({
required: { message: You must enter a name. }
});
self.State = ko.observable().extend({
required: { message: You must select a state. }
});

self.Errors = ko.validation.group(self);
}

ko.validation.configure({
messagesOnModified: true,
insertMessages: true
});

ko.applyBindings(new ViewModel(), document.body);


And jsfiddle to show the difference between the text box and drop down list: http://jsfiddle.net/f7v4m/



The text box is displaying the correct behavior, where the error message will only display after the value has been modified.



Why is the error message displaying for the drop down list?


More From » knockout.js

 Answers
25

To remove the initlial validation message you need to initialize your State property with an empty string:



self.State = ko.observable().extend({
required: { message: You must select a state. }
});


Demo JSFiddle.



You need to do this because when writing ko.observable() it will be initialized with undefined however when knockout evaluates the value binding it sets State to the currently selected empty option value's which is an empty string.



However undefined is not equal to the empty string it makes your property dirty and it triggers the validation message because the validation plugin thinks that your property has been modified.


[#45591] Thursday, May 1, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daja

Total Points: 407
Total Questions: 103
Total Answers: 103

Location: Ghana
Member since Sun, Mar 27, 2022
2 Years ago
daja questions
Tue, Dec 21, 21, 00:00, 3 Years ago
Thu, Apr 23, 20, 00:00, 4 Years ago
Fri, Sep 6, 19, 00:00, 5 Years ago
Tue, Jul 23, 19, 00:00, 5 Years ago
;