Home > Software engineering >  How can I show an error validation if the input value is duplicate?
How can I show an error validation if the input value is duplicate?

Time:04-03

The user has the possibility to add input fields(max2). I want to show an error validation if in the second input the user enters the same word as the first input.

export default function AddSubtitlesTable() {
  const [inputList, setInputList] = useState([{ items: "" }]);
  // const [errorValidation, setErrorValidation] = useState(false)

  const handleAddClick = () => {
    setInputList([...inputList, { items: "" }]);
  };

  const handleItemChanged = (event, index) => {
    const value = event.target.value;
    const list = [...inputList];

    list[index].items = value;
    setInputList(list)

  }


  const handleRemoveClick = (index) => {
    const list = [...inputList];
    list.splice(index, 1);
    setInputList(list);
  };

My idea is to get a previous value and compare it with the current one, that the user enters. How can I solve this?

CodePudding user response:

Simple, just add the following piece of code to check if your inputList already has that value:

const handleItemChanged = (event, index) => {
    const value = event.target.value;
    const list = [...inputList];
    if(list.filter(f=> f.items === value).length > 0){
        //you can trigger a manual validation
        setErrorValidation(true) 
    }
    else{
        setErrorValidation(false) 
    }
    //this still allows you to enter text on the field
    list[index].items = value;
    setInputList(list)
    
}
  • Related