Skip to main content

uniqueItems()

🧭 API map​

I want to…Details
See every accepted call styleSignatures
See common and advanced usageUsage and behavior
Customize messagesMessage configuration
Understand reactive constraintsReactive behavior
Return to the complete catalogBuilt-in validators

πŸ“ Signatures​

uniqueItems
uniqueItems()
uniqueItems(options)
uniqueItems(propertyKey, options?)
uniqueItems(selectKey, options?)

Property selectors accept keys of the non-nullish item type (keyof NonNullable<TItem>) and read the named property. Function selectors receive each original item, including null and undefined, and may read signals; those signal reads become reactive dependencies of the validator.

πŸ“– Usage and behavior​

Requires every array itemβ€”or a selected item keyβ€”to be unique. It supports direct use, an options factory, a property key selector, and a key-selector function:

const myForm = form({
roles: array(field(''), {
initialValue: ['admin', 'admin'],
validators: [uniqueItems],
}),
labelledRoles: array(field(''), {
initialValue: ['admin', 'admin'],
validators: [uniqueItems({ message: 'Roles must be unique.' })],
}),
explicitRoles: array(field(''), {
initialValue: ['admin', 'admin'],
validators: [uniqueItems()],
}),
contacts: array({
email: field(''),
name: field(''),
}, {
initialValue: [
{ email: 'same@example.com', name: 'First' },
{ email: 'same@example.com', name: 'Second' },
],
validators: [uniqueItems('email')],
}),
products: array(productTemplate, {
initialValue: initialProducts,
validators: [
uniqueItems<Product>(product => `${tenantId()}:${product.sku}`),
],
}),
});

Calling uniqueItems() without arguments is equivalent to direct [uniqueItems]. Without a key selector, comparison uses SameValueZero like Set: NaN matches NaN, 0 matches -0, and objects compare by reference. Property and function key selectors compare their derived keys; key-selector functions may read signals reactively.

null and undefined pass as empty arrays. Empty and one-item arrays pass. A failure is { kind: 'uniqueItems', duplicateIndexes, message }. It belongs to the array node and reports every participating index in ascending order while deliberately omitting duplicate values.

Nullable items​

With a property selector such as uniqueItems('id'), a null or undefined item has the key undefined, like item?.id. These items participate in duplicate detection; objects with a missing or undefined id share that key. An object with id: null has the distinct key null.

ValuesResult with uniqueItems('id')
[{ id: 'a' }, null]Valid
[null, undefined]Invalid; duplicate indexes [0, 1]
[null, {}]Invalid; duplicate indexes [0, 1]
[{ id: null }, null]Valid

Duplicates produce a normal validation error without throwing or logging a warning. Validation preserves the supplied values. Use a separate rule if every item must have an ID. Nullable rows can be represented by a field template or by an array value stored in a field; object-form row templates still require object values.

unique-items-nullable.example.ts
import { array, field, form, uniqueItems } from '@ngblocks/form-nodes';

type Selection = { id?: string | null } | null | undefined;

const profile = form({
selections: array(field<Selection>(null), {
initialValue: [
{ id: 'ada' },
null,
],
validators: uniqueItems('id'),
}),
});
profile.valid(); // true

if (!profile.valid()) {
throw new Error('One missing key must be allowed alongside a distinct ID.');
}

profile.selections.set([null, undefined]);
profile.selections.getError('uniqueItems')?.duplicateIndexes; // [0, 1]
profile.invalid(); // true

const duplicates = profile.selections.getError('uniqueItems')?.duplicateIndexes;
if (duplicates?.length !== 2 || duplicates[0] !== 0 || duplicates[1] !== 1 || !profile.invalid()) {
throw new Error('Repeated undefined keys must produce a validation error on the array.');
}
if (profile.selections[0]?.() !== null || profile.selections[1]?.() !== undefined) {
throw new Error('Uniqueness validation must preserve the supplied nullable values.');
}

profile.selections.set([
{ id: null },
null,
]);
profile.valid(); // true

if (!profile.valid() || profile.allErrors().length !== 0) {
throw new Error('A null ID must remain distinct from a missing item key.');
}

Without a selector, uniqueItems() compares the items themselves: null and undefined are distinct, so [null, undefined] passes. A selector callback receives the original values and must handle nullable items itself; for example, item => item?.id uses the property-selector policy.

πŸ’¬ Message configuration​

Every failure has a default English message. Where supported, pass a string as the final argument or use an options object for a static or reactive message, as shown above.

A message function may read signals. Returning undefined continues through node, Angular provider, process-wide, and built-in message fallbacks. See Validator messages.

⚑ Reactive behavior​

The options object accepts a reactive when predicate. Signals read from its validator context are tracked; while it returns false, the rule contributes neither errors nor constraint metadata.

const enforceUniqueRoles = signal(false);
const roles = field(['admin', 'admin'], [
uniqueItems({ when: () => enforceUniqueRoles() })
]);

Reactive constraint functions and message functions track the signals they read. When a resolved constraint becomes unavailable, validators that support optional constraint sources temporarily stop contributing their error and metadata.

The validator runs synchronously as part of its node's validator source. Disabled, readonly, and hidden nodes skip validation until they become interactive again.