簡體   English   中英

如何實現骨干.js驗證/自定義驗證?

[英]How to implement backbone.js validations/custom validations?

需要使用主干驗證js根據另一個字段的值來驗證一個字段。 如何處理呢? 是否可以使用lib方法(例如范圍驗證器,最大驗證器)進行驗證,或者我應該使用自定義方法?

通常是這樣

bindings: {

    'value1': {

        Observe: 'value1',

        Setoptions:{

            Validate:true

        }

    }
}

這將調用validate方法

Validation: {

    Value1: {

        Pattern: number,

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

    }
}

謝謝

我看不到適合比較兩個值的任何內容,請參見內置的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';
        }
    }
});

您可以使用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';
    }
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM