KO验证不在Jquery自动完成输入

时间:2016-09-06 14:28:24

标签: javascript knockout.js jquery-ui-autocomplete knockout-validation

我正在尝试在自动完成输入上使用KO验证。如果他没有从自动填充输入中选择一个值,则该想法是阻止用户提交表单。

验证工作正常,但在验证失败时我无法显示实际的验证消息。 ('从自动填充结果中选择现有ID')

var ViewModel = function() {
    var self = this;
    this.objectValue = ko.observable();    
    this.templateValue = ko.observable();        
    this.selectedID = ko.observable(null);

    this.objectChoices = [];
    this.stringChoices = [];

    for (var i = 0; i < 100; i++) {
        this.objectChoices.push({ id: i, name: "item " + i, myLabel: "item label " + i });
        this.stringChoices.push("item " + i);
    }
  
    this.templateValue.subscribe(function(val){
        self.selectedID(val.id);
    });

    this.submit = function(){
      var validationObj = ko.validatedObservable({
            property1: self.templateValue.extend({
                validation: {
                    validator: function (val) {
                        return self.selectedID() !== null;
                    },
                    message: 'Select an existing ID from autocomplete results'
                }
            })
        });

        if (validationObj.errors().length) {
            validationObj.errors.showAllMessages();
            alert("Error! It should have shown the validation message");
            return false;
        } else {
            alert("No validation errors!");
            return true;
        }
    };
};

ko.applyBindings(new ViewModel());
<link href="https://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.1/knockout.validation.js"></script>
<script src="https://rawgit.com/rniemeyer/knockout-jqAutocomplete/master/build/knockout-jqAutocomplete.js"></script>

<input data-bind="jqAuto: {
    source: objectChoices,
    value: templateValue,
    inputProp: 'name',
    template: 'itemTmpl'
}" />

<script id="itemTmpl" type="text/html">
<a>
    <strong data-bind="text: id"></strong>
    <em data-bind="text: name"></em>
</a>
</script>

<button data-bind="click: submit">submit</button>

请检查小提琴:https://jsfiddle.net/orgvhw84/1/

0 个答案:

没有答案