How to call an attribute from the same model for a validation with ember-cp-validation

506 Views Asked by At

is there a way to call an attribute from the same model? Because I want to use an attribute, from model/code.js, to calculate the validator of an other attribute from the same file. I'll show you with example.

//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'),
});

So as you can see, I want to call nbBits, to have a specific validation for cardId.
Does somebody know the methods or give me a tips? Thank you for your time

1

There are 1 best solutions below

4
On BEST ANSWER

Your case is described in the official documentation of ember-cp-validations as follows:

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
  })
});

Your yet simpler case would look like this:

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')
                }
            ]
        }
    }
);