decide.nolog.cz/app/validators/unique.js

52 lines
1.5 KiB
JavaScript
Raw Normal View History

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';
@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
);
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;
}
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) {
return this.createErrorMessage('unique', value, options);
2016-05-20 21:49:29 +02:00
} else {
return true;
}
}
}