Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

validator : add custom unique validator for complex object. #189

Merged
merged 1 commit into from
Jun 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions projects/rero/ng-core/src/lib/record/editor/editor.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,31 @@ export class EditorComponent implements OnInit, OnChanges, OnDestroy {
};
delete formOptions.validation.validators.valueAlreadyExists;
}
// asyncValidators: valueKeysInObject
// This validator is similar to uniqueValidator but only check on some specific fields of array items.
if (formOptions.validation.validators.uniqueValueKeysInObject) {
field.validators = {
uniqueValueKeysInObject: {
expression: (control: FormControl) => {
// if value isn't an array or array contains less than 2 elements, no need to check
if (!(control.value instanceof Array) || control.value.length < 2) {
return true;
}
const keysToKeep = formOptions.validation.validators.uniqueValueKeysInObject.keys;
const uniqueItems = Array.from(
new Set(control.value.map((v: any) => {
const keys = keysToKeep.reduce((acc, elt) => {
acc[elt] = v[elt];
return acc;
}, {});
return JSON.stringify(keys);
})),
);
return uniqueItems.length === control.value.length;
}
}
};
}
// validators: add validator with expressions
const validatorsKey = Object.keys(formOptions.validation.validators);
validatorsKey.map(validatorKey => {
Expand Down
4 changes: 4 additions & 0 deletions projects/rero/ng-core/src/lib/record/editor/extensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,10 @@ export function registerTranslateExtension(translate: TranslateService) {
name: 'uniqueItems',
message: () => translate.stream(_('should NOT have duplicate items'))
},
{
name: 'uniqueValueKeysInObject',
message: () => translate.stream(_('should NOT have duplicate items'))
},
{
name: 'alreadyTaken',
message: () => translate.stream(_('the value is already taken'))
Expand Down