Check for duplicates in array

default discord avatar
quick007last year
2

Hi all, I was wondering how to check for duplicates in the array type, since validate only returns the number of items in the array

  • discord user avatar
    jesschow
    10 months ago

    Hi @Lukas, you can use the

    validate

    function on the field to pass your own custom validation logic:



    Something like this:


    validate: (val) => {
      // return values from unique field
      const values = val?.map((row) => row.fieldToCheck)
      // check if there are any duplicate values
      const hasDuplicates = new Set(values).size !== values?.length
    
      if (hasDuplicates) return 'Duplicate values in array'
      if (!hasDuplicates) return true
    },


    Sorry you didn't get a reponse here sooner! Let us know if you need anything else.

  • default discord avatar
    quick00710 months ago

    Thanks so much! Better late than never

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.