如何实现backbone.js验证/自定义验证?

时间:2015-06-23 07:48:52

标签: jquery backbone.js requirejs marionette backbone.validation.js

需要使用骨干验证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 */

    }
}

由于

2 个答案:

答案 0 :(得分:0)

我没有看到任何适合比较两个值的内容,请参阅built-in-validatiors

如果使用重复,您可以使用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';
        }
    }
});

答案 1 :(得分: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';
    }
  }
});