KnockoutJS:仅在绑定控件可见时验证模型的属性 [英] KnockoutJS : Validate model's property only if the bound control is visible

查看:69
本文介绍了KnockoutJS:仅在绑定控件可见时验证模型的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个绑定到多个控件的页面中有模型。基于某些条件,这些控件中的一些将是可见的或不可见的。在最终提交时,我应该只验证那些可见的。

I have model in a page that is bound to several controls. Based on some condition some of these controls will be visible or invisible. And on the final submit I should only validate those which are visible.

以下是解释我的要求的示例代码

The following is a sample code to explain my requirement

<script src="knockout-3.4.0.js" type="text/javascript"></script>
    <input type="checkbox" data-bind="checked:requireAge"  >Age Required</input><br />
    Name : <input data-bind="value:Name" /><br />
    <div data-bind="visible:requireAge">
        Age: <input data-bind="value:Age,visible:requireAge" />
    </div>

    <button type="button" onclick="validateModel();">Validate</button>
    <script type="text/javascript">
        var viewModel = { Name: ko.observable(), Age: ko.observable(),requireAge:ko.observable(false) };
        ko.applyBindings(viewModel);
        function validateModel() {
            //validate visible properties and throw a common message that all visible fields should be filled
        }
    </script>


推荐答案

我的建议是使用敲除验证库(你在你的问题中没有提到它,所以我假设你还没有使用它。它与淘汰赛无缝结合,使验证更加方便。我在过去的一年里广泛使用它,它让我的生活变得更加容易。无需创建计算以跟踪observable是否包含有效值。您可以在 github 上找到淘汰验证库。

My suggestion is to use the knockout-validation library (you made no mention of it in your question so I assume you're not using it already) It ties in seamlessly with knockout and makes validation far more convenient. I've used it extensively over the past year and its make my life a whole lot easier. No need to create computeds to keep track of whether an observable contains a valid value or not. You can find the knockout-validation library on github.

在您的情况下,您可以简单地执行以下操作:

In your case you can simply do the following:

var viewModel = function(){ 
  var self = this;
  self.name = ko.observable();      
  self.requireAge = ko.observable(false);
  self.age = ko.observable().extend({ 
      required: {  
        onlyIf: function() { return self.requireAge(); } 
    } 
  });
};

验证错误消息会自动插入到observable绑定的元素下面。您也可以创建自己的验证规则,但有很多可以直接使用,包括上面演示的那些。您甚至可以为某些规则使用某些数据属性。这可能是与淘汰赛一起进行验证的最佳方式。

Validation error messages are inserted automatically below the element the observable is bound to. You can also create your own validation rules but there are many that work straight out the box including the one demonstrated above. You can even use some data attributes for some rules. This is probably the best way to go about validation in conjunction with knockout.

这篇关于KnockoutJS:仅在绑定控件可见时验证模型的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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