Search code examples
sanity

How to create a unique number in Sanity.io?


I have a field of the type number defined on a document in my schema. When the user inputs a number, I want a validation which verifies that no another document of the same type has the same number assigned to this field. How am I able to do this?


Solution

  • There's no out of the box solution to check for uniqueness. Currently the only input that does this is the slug field. However, you can create your own custom validation that uses the client to check for other documents with the same number for the specific field.

    You can read more about custom validation in the docs. To import the client, you can add this to the top of your schema import client from 'part:@sanity/base/client'. Then, write a GROQ query to look for the number and validate accordingly.

    Hope that helps!