淘汰赛验证

Kur*_*ula 46 validation knockout.js knockout-validation

我有asp.net mvc3项目,我在一个带有敲除绑定的表上进行批量编辑.我想在保存数据时进行必需和数字验证等验证.是否有更简单的方法来敲除验证.PS:我没有使用表格.

Coh*_*hen 83

看看Knockout-Validation,它可以干净地设置并使用淘汰文档中描述的内容.在:实例1:强制输入为数字

你可以在Fiddle看到它

更新:小提琴已更新为使用最新的KO 2.0.3和ko.validation 1.0.2使用cloudfare CDN网址

要设置ko.validation:

ko.validation.rules.pattern.message = 'Invalid.';

ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: null
});
Run Code Online (Sandbox Code Playgroud)

要设置验证规则,请使用扩展程序.例如:

var viewModel = {
    firstName: ko.observable().extend({ minLength: 2, maxLength: 10 }),
    lastName: ko.observable().extend({ required: true }),
    emailAddress: ko.observable().extend({  // custom message
        required: { message: 'Please supply your email address.' }
    })
};
Run Code Online (Sandbox Code Playgroud)

  • 它是我还是IE9和IE10上的小提琴?适用于Chrome和Firefox. (2认同)
  • @rob:为了让它在IE中运行,我已经删除了资源并将knockout.validation复制到小提琴中(丑陋,我知道),它确实有效:http://jsfiddle.net/KHFn8/1369/ (2认同)
  • 谢谢科恩.所以现在我有信心它会在我的网站上工作,即使它在jsfiddle上很难看.:-) (2认同)
  • JS Fiddles通过GitHub链接到Knockout文件 - 旧版本不再托管.(许多链接的示例引用v2.1,它现在在v2.2上.它们也不再托管knockout-latest.js). (2认同)

小智 5

如果您不想使用KnockoutValidation库,您可以编写自己的库.以下是必填字段的示例.

添加包含所有KO扩展程序或扩展程序的javascript类,并添加以下内容:

ko.extenders.required = function (target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
    target.hasError(newValue ? false : true);
    target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
    }

    //initial validation
    validate(target());

    //validate whenever the value changes
    target.subscribe(validate);

    //return the original observable
    return target;
};
Run Code Online (Sandbox Code Playgroud)

然后在你的viewModel中通过以下方式扩展你的observable:

self.dateOfPayment: ko.observable().extend({ required: "" }),
Run Code Online (Sandbox Code Playgroud)

这种验证方式有许多在线示例.