Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top