0

需要使用主干验证js根据另一个字段的值来验证一个字段。如何解决这个问题?是否可以使用范围验证器、最大验证器等 lib 方法进行验证,或者我应该使用自定义方法吗?

正常情况下是这样的

bindings: {

    'value1': {

        Observe: 'value1',

        Setoptions:{

            Validate:true

        }

    }
}

这将调用验证方法

Validation: {

    Value1: {

        Pattern: number,

        Min: 0
        /* here we need to validate value1 < value2 where value 2 is value of another input field */

    }
}

谢谢

4

2 回答 2

0

我没有看到任何适合比较两个值的东西,请参阅内置验证器

custom validator如果使用是重复的,您可以使用。在这里使用validator method

Backbone.Model.extend({
    validation: {
      value1: function(value, attr, computedState) {
          if(value < computedState.value2) {
            return 'Error message';
          }
      }
    }
});

named method validator你也可以使用

Backbone.Model.extend({
    validation: {
      value1: {
          min: 0,
          pattern: 'number',
          fn: 'greaterThan'
      }
    },
    greaterThan: function(value, attr, computedState) {
        if(value < computedState.value2) {
          return 'Error message';
        }
    }
});
于 2015-06-23T11:14:43.973 回答
0

您可以使用https://github.com/thedersen/backbone.validation 并使用以下两种情况之一:

https://github.com/thedersen/backbone.validation#do-you-support-conditional-validation

validation: {
  attribute: {
    required: function(val, attr, computed) {
      return computed.someOtherAttribute === 'foo';
    },
    length: 10
  }
}

或者

https://github.com/thedersen/backbone.validation#can-i-call-one-of-the-built-in-validators-from-a-custom-validator

_.extend(Backbone.Validation.validators, {
  custom: function(value, attr, customValue, model) {
    return this.length(value, attr, 4, model) || this.custom2(value, attr, customValue, model);
  },
  custom2: function(value, attr, customValue, model) {
    if (value !== customValue) {
      return 'error';
    }
  }
});
于 2015-06-23T18:05:31.650 回答