sanity-io / sanity-plugin-internationalized-array

A plugin to register array fields with a custom input component to store field values in multiple languages, queryable by using the language ID as an array `_key`.
MIT License
41 stars 10 forks source link

Validation for translatable fields? #64

Closed notflip closed 4 months ago

notflip commented 4 months ago

Is your feature request related to a problem? Please describe. Is it possible to validate the entry of a translated field? For example:

Describe the solution you'd like Having validation: (Rule) => Rule.required(), work on the internationalizedArrayString field

SimeonGriggs commented 4 months ago

Sure, add validation to the top level array item, you can even return item-specific paths with an error message.

Screenshot 2024-03-18 at 15 14 27

    defineField({
      name: 'title',
      type: 'internationalizedArrayString',
      description: `Catch the reader's eye. Use fewer than 5 words.`,
      validation: (rule) =>
        rule.custom<{value: string; _type: string; _key: string}[]>((value) => {
          if (!value) {
            return 'Title is required'
          }

          const invalidItems = value.filter((item) => item.value.split(' ').length > 5)

          if (invalidItems.length) {
            return invalidItems.map((item) => ({
              message: `Title "${item.value}" is too long. Must be 5 words or fewer.`,
              path: [{_key: item._key}, 'value'],
            }))
          }

          return true
        }),
    }),
SimeonGriggs commented 4 months ago

Added this example to the Readme now too :)

https://github.com/sanity-io/sanity-plugin-internationalized-array?tab=readme-ov-file#validation-of-individual-array-items

notflip commented 4 months ago

Beautiful, thanks! @SimeonGriggs I'm loving Sanity so far, certainly so with this nice way of handling translations

fvieira commented 1 month ago

@SimeonGriggs Your suggestion works, but I can't seem to see the error message inline in the field (with the icon, like with normal validations), the field is just red and the message is only in the validations sidebar. Should open a new issue for this?