Folder with the same name

Hi, community,
I have found an awesome article about creating a folder based on filled-in data in the form:
Organize related files in folders on a SharePoint form — SharePoint forms (plumsail.com)
It works perfectly as I expected, but when someone fills in two fields which is the folder based on like this:

  1. Name - Stepan
  2. Surname - Steve
    Save the newForm, it automatically redirects him to "editForm" that I made as a function in custom JS, the folder shows itself with the name "Stepan Steve" linked to the form - Perfect.

So now, the folder exists with the name "Stepan Steve" and now I am going to the newForm again (to create a new item) and fill in these two data fields with the same values:

  1. Name - Stepan
  2. Surname - Steve
    It will not create the folder with the same name. I think it's because it already exists. I need some idea, how to catch the error and warn the user, that the folder "Stepan Steve" is already being used by another form etc.,..

I hope the description is understandable.
Thank you
Stepan

fd.spBeforeSave(function () {
let nameOfFolder = fd.field("sgUzivatel").value.DisplayText + " - " + fd.field("txtRZVozidla").value;
console.log(nameOfFolder);

let createFolder = pnp.sp.web.lists.getByTitle("SmlouvyDokumenty").rootFolder.folders.add(nameOfFolder);
return Promise.allSettled([createFolder]).then((values) => {
console.log(values);
});
});

Hello @Stepan,

You can check if the folder exists or not with PnPjs request. You can replace the save button funcunality with the custom code like this:

var itemExists = false;
fd.spRendered(function() {
    //change click function
    fd.toolbar.buttons[0].click = function() {
        pnp.sp.web.lists.getByTitle("Documents").rootFolder.folders().then(function(items) {
            items.forEach(function(i) {
                if (i.Name == fd.field('Title').value) {
                    itemExists = true;
                    fd.isValid;
                } else {
                    itemExists = false;
                    fd.save();
                }
            });
        });
    }

    fd.validators.push({
        name: 'FolderExistsValidator',
        error: "Folder already exists",
        validate: function(value) {
            return !itemExists;
        }
    });
});