Coding an input box for a unique username

I have a page for users to update their profiles that includes an “'#inputAlias” input text box where they can enter edit their existing profile alias/username. The input box shows their existing alias as a placeholder and an onChange() event triggers the code below, which ensures that any alias the user submits is unique. When the user is ready, they click a submit button and the Profiles collection is updated.

The code works fine. But one problem - if the user enters the same alias as their existing alias the query will flag it as already in use, forcing them to change to a new alias.

export async function inputAlias_change(event) {
await wixData.query("Profiles")
  .eq("alias", $w("#inputAlias").value)
  .find()
  .then( (results) => {
    if (results.items.length > 0) {
      console.log("This alias is already in use");
    //additional code to handle a duplicate alias
    } else {
     console.log("This alias is available");  
    }
  })
  .catch((err) => {
    console.log(err);
  });
}

Note: The “#inputAlias” element is part of a profile-editing page. I tried using a beforeInsert() data hook and backend code, but I prefer an onChange() event as it lets users know right away whether the alias they have entered is acceptable, instead of when the form is complete and a submit button pressed.

Hi, Baksheesh !!

I have a question. In your ‘Profile’ collection, aside from the ‘alias’ field, what other fields are present? Are you not combining it with something like a user(member) ID?

Hi. Profiles is an isolated db. None of the fields are connected to Contacts or Members.

Hi, Baksheesh.

If you don’t want anything to happen when an existing alias is entered, you could handle it by returning from the function when an existing alias value is detected, preventing the query from being executed. :smiley:

export async function inputAlias_change(event) {
    if(currentAliasValue === event.target.value) return;
    // query and judge process
}
1 Like

Yes, that makes sense and works. Thank you.

Still having problems with validating the input before it’s written to the dataset – I tried onCustomValidation() and beforeInsert() – but this may be because I’m mixing coded event handlers with text input boxes connected to the CMS in the Editor. Will post if I find a solution.

1 Like