KnockoutValidation 和条件要求规则 [英] KnockoutValidation and the conditional required rule

查看:19
本文介绍了KnockoutValidation 和条件要求规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 KnockoutValidation 与条件语句一起使用.见下面的代码:

I am trying to use KnockoutValidation with conditional statements. See code below:

self.transactionType = ko.observable('Option1');

self.ConditionalField = ko.observable().extend({
  required: true, 
  onlyIf: self.transactionType = ="Option2"
});

不幸的是,这不起作用.我希望 ConditionalField 仅在 transactionType 具有值 'Option2' 时才需要.

Unfortunately this doesn't work. I want to have ConditionalField only required if transactionType has value 'Option2'.

在knockout.validation.js 中使用条件验证的最佳方法是什么?

What is the best way to use conditional validation with knockout.validation.js?

推荐答案

我已经解决了.

首先,我在定义了conditionalfield 之后,错误地声明了transactiontype.有效的最终代码如下所示:

First of all I made the mistake of declaring the transactiontype after I had defined the conditionalfield. The end code that works looks like this:

self.transactionType = ko.observable("Option1");

self.conditionalField = ko.observable().extend({
  required: {
    onlyIf: function () { 
      return self.transactionType () == "Option2";
    }
  }
});

这篇关于KnockoutValidation 和条件要求规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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