0

让我分享一下我很久以前偶然发现并在今天解决的问题。

问题描述:

每次相关键更改时都不会执行验证器。

我的自定义验证器检查自定义元的唯一性定义如下:

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

});

验证器恰好执行了两次,尽管依赖键更频繁地更改。我认为问题可能来自在与其他功能相关的相同条件下触发的模型片段插件或观察者。

这是我的验证声明:

const Validations = buildValidations({
  customMeta: {
    description: 'Custom-metas',
    validators: [
      validator('unique-custom-meta-key', {
        dependentKeys: ['customMeta.@each.key'],
        debounce: 500
      })
    ]
  }
});

和模型定义:

export default Model.extend(Validations, {
  customMeta : fragmentArray('custom-meta')
});
4

1 回答 1

1

解决方案:

在查看ember-cp-validation代码后,我注意到声明一个依赖于集合中多个值的验证器的区别:

dependentKeys: ['model.friends.@each.name']

如您所见,model依赖键声明中的属性起到了作用。如今,他们的在线文档也提供了正确的声明,当我第一次偶然发现这个问题时,情况并非如此。

dependentKeys: ['model.customMeta.@each.key'],

非常愚蠢的错误,但也许这个线程可以挽救某人的一天;-)

于 2017-03-03T11:27:32.380 回答