-
Notifications
You must be signed in to change notification settings - Fork 33
Unique value in CollectionField form
Geoff Cox edited this page Dec 20, 2020
·
6 revisions
Sometimes you want to prevent duplication of values within a collection. For example, let's say that you have a collection of items and want every item to have a unique firstName
. You can achieve this by using the parent
keyword in a validator with the $elemMatch
operator, e.g.
{
component: "CollectionField",
name: "contacts",
label: "Contacts",
formFactory: {
component: "Factory",
product: {
component: "Form",
fields: [
{
// Unique id per item so that duplication is only considered
// when the id is different
name: "id",
component: "UUIDField",
label: "Id",
hidden: true
},
{
name: "firstName",
component: "TextField",
label: "First Name"
},
{
name: "birthday",
component: "DateField",
label: "Birthday"
}
],
validators: [
{
where: {
"parent.value": {
$elemMatch: {
$and: [
{
// Only consider duplication when the id doesn't match
id: {
$ne: "{{fields.id.value}}"
}
}
{ name: "{{fields.firstName.value}}" }
]
}
}
},
error: {
field: "firstName",
error: "must be unique"
}
}
]
}
}
}