Knockout Validation isValid always returns true

冷暖自知 提交于 2019-12-24 07:46:23

问题


I am new to using knockout and I am trying to get the validation plug-in to work. However, IsValid is always returning turn. I have also tried ViewModel.errors().length == 0 but it is always zero

Here is the rest of my code, please help.

    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:


ViewModel is just a constructor not an instance of your implemented model. So you applied errors properties to constructor and also tried to validate this constructor that does not sense.

Change ViewModel to self in save method:

    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();
        }
    };

..and:

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


来源:https://stackoverflow.com/questions/20256979/knockout-validation-isvalid-always-returns-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!