Knockout Validation on drop down list always displaying error message
Asked Answered
E

1

6

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?

Eurhythmic answered 2/5, 2014 at 18:28 Comment(1)
Possible duplicate of Knockout validation on my dropdown don't workEvolution
D
13

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.

Douglass answered 2/5, 2014 at 18:38 Comment(3)
Doesn't work when combined with options and optionsCaption bindings. jsfiddle.net/7UzH9/12Counterattraction
Found a solution for optionsCaption binding. You need to initialize observable to undefined like this: ko.observable(undefined).extend({ .. }); jsfiddle.net/7UzH9/13Counterattraction
@Counterattraction The above fix is when not using the options binding. Also you don't need to specify undefined as undefined is the default for observablesPacifistic

© 2022 - 2024 — McMap. All rights reserved.