如何使用 ember-cp-validation 从同一模型调用属性进行验证
How to call an attribute from the same model for a validation with ember-cp-validation
有没有办法从同一模型调用属性?因为我想使用 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.
进行特定验证
有人知道这些方法或给我提示吗?谢谢你的时间
你的案例在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')
}
]
}
}
);
有没有办法从同一模型调用属性?因为我想使用 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.
进行特定验证
有人知道这些方法或给我提示吗?谢谢你的时间
你的案例在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')
}
]
}
}
);