将两个字段与敲除验证进行比较

Mat*_*att 5 knockout.js knockout-validation

我有一个表单的viewmodel,我正在尝试使用knockout-validation添加验证.

fromDate: ko.observable(
            moment().subtract('days', 1).startOf('day').format(dateFormat)
          ),
toDate: ko.observable(
            moment().startOf('day').format(dateFormat)
        ),
Run Code Online (Sandbox Code Playgroud)

我需要确保起始日期小于到目前为止.我似乎无法获得任何形式的自定义验证器来获取对第二个observable的引用.我需要的东西是:

toDate: ko.observable(moment().startOf('day').format(dateFormat)).extend({
          validation: {
            validator: function (val, someOtherVal) {
                return moment(val) >= moment(someOtherVal);
            },
            message: 'Must be greater or equal to From Date',
            params: viewModel.fromDate()
          }
        }),
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

更新

我确定我已经尝试过这个,但是将扩展方法移动到onload函数是有效的.

$(function () {
    ko.validation.configure({ decorateElement: true });

    viewModel.toDate.extend({
    validation: {
            validator: function (val, someOtherVal) {
                return moment(val) >= moment(viewModel.fromDate());
            },
            message: 'To date must be greater than from date',
        }
    });

    ko.applyBindings(viewModel);
});
Run Code Online (Sandbox Code Playgroud)

del*_*xfe 6

knockout-validation的核心规则无法将observable作为验证参数处理.但是已经有一个推送请求应该解决这个问题:https://github.com/ericmbarnard/Knockout-Validation/pull/217

因此,您必须使用自定义角色.您应该将param作为函数插入(通过省略括号).这将使敲除验证能够对参数的变化作出反应.

function ViewModel() {
    var self = this; // capture this to be able to reference properties

    self.fromDate = ko.observable(
        moment().subtract('days', 1).startOf('day').format(dateFormat)
    );
    self.toDate = ko.observable(
        moment().startOf('day').format(dateFormat)
    ).extend({
      validation: {
        validator: function (val, someOtherVal) {
            return moment(val) >= moment(someOtherVal());
        },
        message: 'Must be greater or equal to From Date',
        params: self.fromDate
      }
    }),
}
Run Code Online (Sandbox Code Playgroud)


Pau*_*tti 3

查看它的文档,这看起来像您可以做到的方式:

ko.validation.rules['greaterThan'] = {
    validator: function (val, otherVal) {
        return val > otherVal;
    },
    message: 'The field must be greater than {0}'
};

ko.validation.registerExtenders();

fromDate: ko.observable(
            moment().subtract('days', 1).startOf('day').format(dateFormat)
          ),
toDate: ko.observable(
            moment().startOf('day').format(dateFormat)
        ).extend({ greaterThan: fromDate() });
Run Code Online (Sandbox Code Playgroud)

它未经测试,我不知道你是否想传入 fromDate(),或 fromDate 然后在验证器中使用 otherVal()。

  • Paul 的答案中的最后一行应该如下所示: ).extend({greaterThan: this.fromDate }); 即参数必须在没有括号的情况下传递。第三行应如下所示: return val > otherVal(); -- otherVal 带括号。这样就可以了。 (3认同)