Knockout Validation evaluates immediately on load

后端 未结 3 1754
Happy的楠姐
Happy的楠姐 2020-12-18 19:21

I\'m using MVC, Knockout, and Knockout Validation to validate my view model.

I\'m running into an issue where the validation for view model properties are firing imm

相关标签:
3条回答
  • 2020-12-18 19:40

    Quoting KO page.... ( http://knockoutjs.com/documentation/options-binding.html )

    KO will prefix the list of items with one that displays the text “Select an item…” and has the value undefined. So, if myChosenValue holds the value undefined (which observables do by default), then the dummy option will be selected. If the optionsCaption parameter is an observable, then the text of the initial item will update as the observable’s value changes.

    So, I solved it by setting "undefined" when defining the property, see example below:

    self.myProperty = ko.observable(undefined).extend({
        required :  {"Field Required"}
    });
    

    Hope this helps...

    0 讨论(0)
  • 2020-12-18 19:48

    I figured out this issue on my own.

    The problem exists between the razor engine templating the select options, and then later binding the value of the selected element to Knockout.

    Despite the fact that there is no user-inputted value in the select box, the default value, the "--select--" actually contains a value. In my case it was an empty string. Therefore, when I applied the knockout bindings, my viewmodel property was "updated" with the empty string value, and therefore validation fired.

    To get around this in my case I set the default value of my model to be an empty string. Therefore when the bindings are applied, there is no valueHasMutated event fired on the Knockout observable, and thus no validation.

    0 讨论(0)
  • 2020-12-18 19:51

    After applying the bindings for the viewmodel. Then for that viewmodel make showAllMessages as false

    Example

    YourViewmodelname.errors.showAllMessages(false);
    
    0 讨论(0)
提交回复
热议问题