Knockout Validation isValid always returns true

2019-08-07 06:35发布

问题:

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