Let me share the problem I stumbled upon longer ago and fixed today.
Problem description:
Validator not executed everytime dependent keys changed.
My custom validator checking uniqueness of custom-meta keys is defined as follows:
import BaseValidator from 'ember-cp-validations/validators/base';
import Ember from 'ember';
const {isEqual} = Ember;
export default BaseValidator.extend({
/**
* Validates custom-metas of the {spot} model.
* The validation leans upon duplicates detection of the 'key' property values.
* @example:
* spot.set('customMeta', [{key: 'duplicate'}, {key: 'duplicate'}]);
* spot.get('validations.attrs.customMeta.isValid') -> false
* spot.set('customMeta', [{key: 'unique 1'}, {key: 'unique 2'}]);
* spot.get('validations.attrs.customMeta.isValid') -> true
* ...skipping rest of the doc...
*/
validate(value, options, spot) {
const customMetaKeys = spot.get('customMeta').mapBy('key');
if(isEqual(customMetaKeys.get('length'), customMetaKeys.uniq().get('length'))){
return true;
}
return this.createErrorMessage('unique-custom-meta-keys', value, options);
}
});
The validator was executed exactly twice although the dependent keys have changed more often. I thought the problem could come from model-fragments addon or observer that was fired on the same conditions which was related to other feature.
This was my validation declaration:
const Validations = buildValidations({
customMeta: {
description: 'Custom-metas',
validators: [
validator('unique-custom-meta-key', {
dependentKeys: ['[email protected]'],
debounce: 500
})
]
}
});
and model definition:
export default Model.extend(Validations, {
customMeta : fragmentArray('custom-meta')
});
Solution:
After looking into ember-cp-validation code I noticed a difference in declaring a validator that depends on multiple values from the collection:
As you can see, the
model
property in the dependent keys declaration did the trick. Nowadays also their online doc provide a correct declaration which wasn't the case back then when I stumbled upon the problem for the first time.Very stupid mistake, but maybe this thread saves someone's day ;-)