淘汰赛验证isValid始终返回true [英] Knockout Validation isValid always returns true

查看:101
本文介绍了淘汰赛验证isValid始终返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用淘汰赛是陌生的,我正在尝试使验证插件正常工作.但是,IsValid总是回合.我也尝试过 ViewModel.errors().length == 0 但始终为零

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>

推荐答案

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

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.

save方法中将ViewModel更改为self:

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

这篇关于淘汰赛验证isValid始终返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆