挖空.js两个输入字段的逻辑 OR 的自定义验证规则

Knockout.js custom validation rule for logical OR for two input fields

本文关键字:OR 自定义 规则 验证 字段 输入 js 两个 挖空      更新时间:2023-09-26

如何使用挖空.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]});

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

在我为验证提供标题或描述的那一刻,它们尚未初始化。我将代码更改为此代码,现在它可以工作:

//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!"
        }});