针对两个输入字段

时间:2016-02-08 15:16:06

标签: javascript validation knockout.js

如何使用Knockout.js验证两个输入字段?规则是:必须填写至少一个输入字段。

ko.validation.rules['OR'] = {
    validator: function (val, otherVal) {
        return (val || otherVal);
    },
    message: "you have to fill in at least one of the two input fields!"
};

ko.validation.registerExtenders();


self.description = ko.observable().extend({ OR:  self.title });
self.title = ko.observable().extend({ OR:  self.description });

目前:在初始化时,只有一个字段为红色,一个为绿色 - 开始时它们都应为红色。

https://github.com/Knockout-Contrib/Knockout-Validation

 self.title = ko.observable().extend({ OR:  self.description });
 self.description = ko.observable().extend({ OR:  self.title });

title有效,但description在启动时无效。当我将代码顺序更改为:

self.description = ko.observable().extend({ OR:  self.title });      
self.title = ko.observable().extend({ OR:  self.description });
然后是相反的。

即使是KnockOut贡献的例子也不适用于我: https://github.com/Knockout-Contrib/Knockout-Validation/wiki/User-Contributed-Rules

ko.validation.rules['requiresOneOf'] = {
  getValue: function (o) {
    return (typeof o === 'function' ? o() : o);
  },
  validator: function (val, fields) {
    var self = this;

    var anyOne = ko.utils.arrayFirst(fields, function (field) {
      var stringTrimRegEx = /^\s+|\s+$/g,
                testVal;

      var val = self.getValue(field);

      if (val === undefined || val === null) 
        return !required;

      testVal = val;
      if (typeof (val) == "string") {
        testVal = val.replace(stringTrimRegEx, '');
      }

      return ((testVal + '').length > 0);

    });

    return (anyOne != null);
  },
  message: 'One of these fields is required'

};
self.title = ko.observable();
self.description = ko.observable();


self.title.extend({requiresOneOf: [self.title, self.description]});
self.description.extend({requiresOneOf: [self.title, self.description]});

1 个答案:

答案 0 :(得分:0)

我发现了错误。实际上这是一个鸡蛋问题。

当我将标题或描述提供给验证时,它们尚未初始化。我将代码更改为此,现在可以正常运行:

//define the validation rule:
ko.validation.rules['Or'] = {
    validator: function (val, params) {
        "use strict";
        return (val !== "" && val !== undefined) || ( params.other() !== "" && params.other() !== undefined);
    },
    message: "you have to fill in at least one of the two input fields!"
};

ko.validation.registerExtenders();


//apply the validation rule:
 self= this;

    self.description = ko.observable();
    self.title = ko.observable();

    self.title.extend({
        or: {
            params: {other: self.description},
            message: "Please fill at least one field!"
        }
    });

    self.description.extend({
        or: {
            params: {other: self.title},
            message: "Please fill at least one field!"
        }});