【问题标题】:knockout validation is not workong淘汰赛验证不起作用
【发布时间】:2016-02-17 22:03:34
【问题描述】:

我有一个表格要使用 KnockOut JS 进行验证。该表格连同 KnockOut JS 脚本可在此处获得 http://jsfiddle.net/gy8qwLk1/ 我想在验证为 true 后提交表单。 这是我的脚本:

    /// <reference path="../Scripts/knockout-3.1.0.js" />
/// <reference path="../Scripts/jquery-1.10.2.js" />
/// <reference path="../Scripts/knockout.validation.js" />

var customerRegisterViewModel;

function Customervalidate(id, customerName, contactName, address, city, postalCode, country) {
    var self = this;
    self.ID = ko.observable(id);
    self.CustomerName = ko.observable(customerName).extend({ required: { message: 'Customer Name is required' } });
    self.ContactName = ko.observable(contactName).extend({ required: true });
    self.Address = ko.observable(address).extend({ required: true });
    self.City = ko.observable(city).extend({ required: true });
    self.PostalCode = ko.observable(postalCode).extend({ required: true });
    self.Country = ko.observable(country).extend({ required: true });
}


function Customer(id, customerName, contactName, address, city, postalCode, country) {
    var self = this;

    self.ID = ko.observable(id);
    self.CustomerName = ko.observable(customerName).extend({ required: {message :'Customer Name is required' }});
    self.ContactName = ko.observable(contactName).extend({ required: true });
    self.Address = ko.observable(address).extend({ required: true });
    self.City = ko.observable(city).extend({ required: true });
    self.PostalCode = ko.observable(postalCode).extend({ required: true });
    self.Country = ko.observable(country).extend({ required: true });

    self.addCustomer = function () {
        var dataObject = ko.toJSON(this);        

            $.ajax({
                url: '/api/customer',
                type: 'post',
                data: dataObject,
                contentType: 'application/json',
                success: function (data) {
                    customerRegisterViewModel.customerListViewModel.customers.push(new Customer(data.ID, data.CustomerName, data.ContactName, data.Address, data.City, data.PostalCode, data.Country));
                    self.ID(null);
                    self.CustomerName('');
                    self.ContactName('');
                    self.Address('');
                    self.City('');
                    self.PostalCode('');
                    self.Country('');
                }
            });
        }

    };



function CustomerList() {
    var self = this;
    // observable arrays are update binding elements upon array changes
    self.customers = ko.observableArray([]);

    self.getCustomers = function () {
        self.customers.removeAll();

        // retrieve students list from server side and push each object to model's students list
        $.getJSON('/api/customer', function (data) {
            $.each(data, function (key, value) {
                self.customers.push(new Customer(value.ID, value.CustomerName, value.ContactName, value.Address, value.City, value.PostalCode, value.Country));
            });
        });
    };



    // remove student. current data context object is passed to function automatically.
    self.removeCustomer = function (customer) {
        $.ajax({
            url: '/api/customer/' + customer.ID(),
            type: 'delete',
            contentType: 'application/json',
            success: function () {
                self.customers.remove(customer);
            }
        });
    };
}
// create index view view model which contain two models for partial views
customerRegisterViewModel = { addCustomerViewModel: new Customer(), customerListViewModel: new CustomerList(),validateModel : new Customervalidate()  };

// on document ready
$(document).ready(function () {
    //ko.applyBindings(customerRegisterViewModel);
    ko.validatedObservable(customerRegisterViewModel);
    ko.applyBindings(customerRegisterViewModel);


    ko.validation.configure({
        registerExtenders: true,
        messagesOnModified: true,
        decorateElement: true,
        errorClass: 'error',
        insertMessages: true,
        parseInputAttributes: true,
        messageTemplate: 'customMessageTemplate'
    });


});

【问题讨论】:

    标签: knockout.js knockout-validation


    【解决方案1】:

    在您的函数“addCustomer”中,我没有看到任何检查验证是否失败的内容......而且还有一些事情需要解决。

      self.errors = ko.validation.group(self);
    
      self.isValid = ko.computed(function(){     
            return self.errors().length == 0;
      });
    
      self.addCustomer = function () {
      if(!self.isValid())
      {
        self.errors.showAllMessages(true);
        return;
      }
    

    框架将生成显示验证消息所需的 UI 元素......因此无需预先创建这些元素。

    您可能需要对脚本进行一些工作,但作为起点,请参阅 jsfiddle http://jsfiddle.net/wfpacsgw/3/ 以获取脚本的工作版本。

    【讨论】:

    • 它在 fiddler 中运行良好。但是当我在 Visual Studio 中运行时,我遇到了“未捕获的类型错误:无法读取未定义的属性“组”错误
    • fiddler 和 Visual Studio 中使用的 ko、ko.mapping 和 ko.validation 库的版本可能不同。确保它们相同。
    • 它们是相同的。我只是复制了您的脚本并将其粘贴到了 Visual Studio。我查看了参考资料,它们是相同的,并且可以在我的 Scripts 文件夹中找到
    • hmmm ...我相信该消息指的是“self.errors = ko.validation.group(self);”这一行它认为 ko.validation 没有定义。这使我相信 ko.validation 库是缺少的库。我能够在提琴手jsfiddle.net/wfpacsgw/4 中重现它(如果您查看 chrome 开发人员控制台,您也可以在那里看到异常)。
    • 在“knockout-validation.js”中定义。因此,您需要在网页中添加对该库的引用才能使用它。
    猜你喜欢
    • 1970-01-01
    • 2014-11-12
    • 1970-01-01
    • 2018-09-16
    • 2016-12-31
    • 2012-02-18
    • 2014-05-10
    • 2016-09-15
    相关资源
    最近更新 更多