如何使用ember-cp-validation从同一模型调用属性进行验证

时间:2017-08-09 08:08:13

标签: validation ember.js ember-data ember-cli ember-cp-validations

有没有办法从同一个模型调用属性?因为我想使用model / code.js中的属性来计算同一文件中其他属性的验证器。我将以示例的方式向您展示。



//model/code.js
import Ember from 'ember';
import DS from 'ember-data';
import {validator, buildValidations} from 'ember-cp-validations';

const CardValidations = buildValidations(
    {
      cardId: {
            validators: [
                validator('presence', true),
                validator('length', {
                    // here instead of 10, I want to use nbBits
                    max: 10
                       
                }
            ]
        }
    }
);

export default Credential.extend(CardValidations, {
    cardId: DS.attr('string'),
    nbBits: DS.attr('number'),

    displayIdentifier: Ember.computed.alias('cardId'),
});




您可以看到,我想调用 nbBits ,对 cardId 进行特定验证。
有人知道方法或给我一些提示吗?谢谢你的时间

1 个答案:

答案 0 :(得分:1)

您的案例在 ember-cp-validations 的官方documentation中有所描述,如下所示:

const Validations = buildValidations({
  username: validator('length', {
    disabled: Ember.computed.not('model.meta.username.isEnabled'),
    min: Ember.computed.readOnly('model.meta.username.minLength'),
    max: Ember.computed.readOnly('model.meta.username.maxLength'),
    description: Ember.computed(function() {
      // CPs have access to the model and attribute
      return this.get('model').generateDescription(this.get('attribute'));
    }).volatile() // Disable caching and force recompute on every get call
  })
});

你更简单的案例看起来像这样:

const CardValidations = buildValidations(
    {
      cardId: {
            validators: [
                validator('presence', true),
                validator('length', {
                    // here instead of 10, I want to use nbBits
                    max: Ember.computed.readOnly('model.nbBits')
                }
            ]
        }
    }
);