I'm trying to validate some fields that are all part of my field array. They have same names, but they have a different array index.
<Select
{...register(`documents.${index}.language`, {
validate: (v) => getValues(v),
})}
sx={{ textAlign: 'center' }}
>
{availableLanguages
?.sort((a) => (a.name === 'pl' ? -1 : 1))
// sorting so pl is default value
.map((language) => (
<option key={language.name} value={language.name}>
{language.name.toUpperCase()}
</option>
))}
</Select>
I want to validate by getting all the language values and check if they are all unique.
The output array creates an object for each field the user has decided to fill in and returns a language value in that object + some others.
[{language: 'en'},{language: 'en'}, {language: 'br'}]
I want to validate this, preferably before submit, meaning that it would have to be done in the validate function of the field.
Other way, I could also validate it on submit, however I'm also not sure how to do this efficiently.
For anyone in the future this is the way I have been able to go around this validation. A simple for loop, there are other ways but they don't actively get the field value unless kept in state.
<Select
{...register(`documents.${index}.language`, {
validate: (v) => {
for (let x = 0; x < index; x++) {
if (v === getValues(`documents.${x}.language`)) return false;
}
},
})}
sx={{ textAlign: 'center' }}
>
{sortLanguages(availableLanguages).map((language) => (
<option key={language.name as string} value={language.name as string}>
{language.name.toUpperCase()}
</option>
))}
</Select>