Knockout Validation isValid始终返回true

时间:2013-11-28 03:03:32

标签: knockout.js knockout-validation

我是使用knockout的新手,我正在努力让验证插件工作。但是,IsValid总是回归。我也试过了     ViewModel.errors()。length == 0 但它始终为零

以下是我的其余代码,请帮助。
         

    ko.validation.configure({
        registerExtenders: true,
        messagesOnModified: true,
        insertMessages: true,
        parseInputAttributes: true,
        messageTemplate: null
    });


    function ViewModel(survey) {
        // Data
        var self = this;


        self.ProjectNumber = ko.observable();
        self.StandardName = ko.observable();
        self.Name = ko.observable().extend({ required: true });

        self.save = function () {
            console.log("Valid: " + ViewModel.errors.length);
            if (ViewModel.errors().length == 0) {
                $.ajax("@Url.Content("~/Survey/TEST/")", {
                    data: ko.toJSON(self),
                    type: "post",
                    contentType: 'application/json',
                    dataType: 'json'
                });
            } else {
                ViewModel.errors.showAllMessages();
            }
        };


    }

    ViewModel.errors = ko.validation.group(ViewModel);

    ko.applyBindings(new ViewModel);
</script>

1 个答案:

答案 0 :(得分:1)

ViewModel只是一个构造函数,而不是您实现的模型的实例。因此,您将errors属性应用于构造函数,并尝试验证此无效的构造函数。

ViewModel方法中将self更改为save

    self.save = function () {
        console.log("Valid: " + self.errors.length);
        if (ViewModel.errors().length == 0) {
            $.ajax("@Url.Content("~/Survey/TEST/")", {
                data: ko.toJSON(self),
                type: "post",
                contentType: 'application/json',
                dataType: 'json'
            });
        } else {
            self.errors.showAllMessages();
        }
    };

..和

// create instance of model
var vm = new ViewModel; 
// setup validation for instance
vm.errors = ko.validation.group(vm);
// apply bindings
ko.applyBindings(vm);
相关问题