how validate input names are not duplicate in react using yup?

Viewed 22

I'm using react/typescript

I have some file validations to perform in a file input. I want to check the names of the files are not duplicated in the upload set.

in the next example I'm testing the file names to match a criteria.

Example: SUPPORTED_NAMES = ["text", "command", "execute"]
test('fileName', 'unsuported file name', (value: FileList)=>{
   for(let i = 0; i < value.lenght; i++){
   const file = value.item(i);
   if(file.name){
    return SUPPORTED_NAMES.some((element) => 
     file.name.includes(element.toLowerCase())
   );
  }
}
 return false;

})

Now I want to check that I don't have duplicated file names... Any ideas?

1 Answers

You can add a custom method to check uniqueness to yup schema and use it like this:

yup.addMethod(yup.array, "unique", function (message, mapper = (a) => a) {
  return this.test("unique", message, function (list) {
    return list.length === new Set(list.map(mapper)).size;
  });
});

const validationSchema = yup
  .array()
  .of(
    yup.object().shape({
      name: yup.string()
    })
  )
  .unique("duplicate name", (a) => a.name);

You can take a look at this sandbox for a live working example of this approach.

Related