2018-12-29 01:27:37 +01:00
|
|
|
import { isArray } from '@ember/array';
|
|
|
|
import { isPresent, isEmpty } from '@ember/utils';
|
|
|
|
import { assert } from '@ember/debug';
|
2016-05-20 21:49:29 +02:00
|
|
|
import BaseValidator from 'ember-cp-validations/validators/base';
|
|
|
|
|
|
|
|
export default BaseValidator.extend({
|
|
|
|
validate(value, options, model, attribute) {
|
2018-12-29 01:27:37 +01:00
|
|
|
assert(
|
2016-05-20 21:49:29 +02:00
|
|
|
'options.parent is required',
|
2018-12-29 01:27:37 +01:00
|
|
|
isPresent(options.parent)
|
2016-05-20 21:49:29 +02:00
|
|
|
);
|
2018-12-29 01:27:37 +01:00
|
|
|
assert(
|
2016-05-20 21:49:29 +02:00
|
|
|
'options.attributeInParent is required',
|
2018-12-29 01:27:37 +01:00
|
|
|
isPresent(options.attributeInParent)
|
2016-05-20 21:49:29 +02:00
|
|
|
);
|
2018-12-29 01:27:37 +01:00
|
|
|
assert(
|
2016-05-20 21:49:29 +02:00
|
|
|
'options.dependentKeys is required',
|
2018-12-29 01:27:37 +01:00
|
|
|
isArray(options.dependentKeys) && options.dependentKeys.length > 0
|
2016-05-20 21:49:29 +02:00
|
|
|
);
|
|
|
|
|
2016-06-21 01:13:09 +02:00
|
|
|
if (options.disable) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2016-05-20 21:49:29 +02:00
|
|
|
// ignore empty values
|
2018-12-29 01:27:37 +01:00
|
|
|
if (isEmpty(value)) {
|
2016-05-20 21:49:29 +02:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
const parent = model.get(options.parent);
|
|
|
|
const collection = parent.get(options.attributeInParent);
|
|
|
|
const positionInCollection = collection.indexOf(model);
|
2016-06-21 01:13:09 +02:00
|
|
|
const elementsBefore = positionInCollection !== -1 ? collection.slice(0, positionInCollection) : collection;
|
2016-05-20 21:49:29 +02:00
|
|
|
const matches = elementsBefore.findBy(attribute, value);
|
|
|
|
|
|
|
|
if (matches) {
|
2016-07-03 16:50:42 +02:00
|
|
|
return this.createErrorMessage('unique', value, options);
|
2016-05-20 21:49:29 +02:00
|
|
|
} else {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|