2020-01-18 10:13:50 +01:00
|
|
|
import classic from 'ember-classic-decorator';
|
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';
|
|
|
|
|
2020-01-18 10:13:50 +01:00
|
|
|
@classic
|
|
|
|
export default class UniqueValidator extends BaseValidator {
|
2016-05-20 21:49:29 +02:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2019-06-14 23:58:53 +02:00
|
|
|
let parent = model.get(options.parent);
|
|
|
|
let collection = parent.get(options.attributeInParent);
|
|
|
|
|
|
|
|
if (options.ignoreNewRecords) {
|
|
|
|
// ignore records while saving cause otherwise the record
|
|
|
|
// being created itself is considered a duplicate while saving
|
|
|
|
collection = collection.filter((_) => !_.isNew);
|
|
|
|
}
|
|
|
|
|
|
|
|
let positionInCollection = collection.indexOf(model);
|
|
|
|
let elementsBefore = positionInCollection !== -1 ? collection.slice(0, positionInCollection) : collection;
|
|
|
|
let matches = elementsBefore.findBy(attribute, value);
|
2016-05-20 21:49:29 +02:00
|
|
|
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|
2020-01-18 10:13:50 +01:00
|
|
|
}
|