Adding a error message when duplicate values with Autocomplete MUI React

34 Views Asked by At

Im having some trouble of how can I control and tell the user that they are setting a duplicate value. By default, if user tries to enter input already at the values list, it wont let you add the "tag". This is fine for me, but in addition i want to add a warning message near the input indicating that no duplicates values are allowed...

    <Autocomplete
      PaperComponent={CustomPaper}
      onChange={(event: any, newValue: string[], reason: string) => {
        handleInputUsersChange(event, newValue, reason);
      }}
      autoComplete
      freeSolo
      fullWidth
      multiple
      id={props.id}
      value={props.initEmails}
      options={listUsers.map((item) => {
        return item.name;
      })}
      renderInput={(params) => {
        return (
          <div ref={params.InputProps.ref} style={{ display: 'flex' }} data-test="test-div-autocomplete-comp">
            <TextField {...params} style={{ width: '1200px' }} />
          </div>
        );
      }}
    />

Im trying to capture the validation or event that Autocomplete uses to not add the duplicated tag, but im not able to...

Thanks in advance

1

There are 1 best solutions below

0
Jamie On

MUI doesn't expose a validation hook, so the best you could do is:

  const initEmails = ["[email protected]"];
  const [emails, setEmails] = useState(initEmails);

  const [duplicateEmailError, setDuplicateEmailError] = useState(false);

  const listUsers = [
    { name: "John Doe", email: "[email protected]" },
    { name: "Jane Doe", email: "[email protected]" },
  ];

  return (
    <Autocomplete
      PaperComponent={Paper}
      onChange={(event, newValue) => {
        setEmails(newValue);
      }}
      onKeyUp={(event: React.KeyboardEvent<HTMLInputElement>) => {
        if (
          event.key === "Enter" &&
          listUsers.some((item) => item.email === (event.target as HTMLInputElement).value)
        ) {
          setDuplicateEmailError(true);
        } else {
          setDuplicateEmailError(false);
        }
      }}
      autoComplete
      freeSolo
      fullWidth
      multiple
      value={emails}
      options={listUsers.map((item) => {
        return item.name;
      })}
      renderInput={(params) => {
        return (
          <div ref={params.InputProps.ref} style={{ display: "flex" }} data-test="test-div-autocomplete-comp">
            <TextField
              {...params}
              style={{ width: "1200px" }}
              error={duplicateEmailError}
              helperText={duplicateEmailError ? "Duplicate Email" : null}
            />
          </div>
        );
      }}
    />
  );

Note the setDuplicateEmailError state, and the validation against the listUsers in the onKeyUp prop.