Home > Mobile >  Why the condition for empty input is not working?
Why the condition for empty input is not working?

Time:03-03

What Im trying to do, is to handle the input from on a handle function. The first condition is for special characters like: ?/., etc. And the second condition is for empty input, in this case, when the user doesn't fill the name form and leave it empty. The action in this code is saving the client to the database.

function onChangeinput(event){
    updateState({ ...formState, [event.target.name]: event.target.value});
    if (event.target.name == "name"){
      setNamefield(event.target.value)

      const regex = /[a-zA-Z0-9_-]/; //for special characters 
      if (regex.test(event.target.value) === false) {
        setErrorMessageName("Max. length: 128 characters. May include numbers, letters");
        setDisableButton(true); 
      }
      else if(event.target.value > 0) {
        setDisableButton(true);
        setErrorMessageName("Input is empty...");
      }
    }
  }

To check if in the input name form is empty, I have put a condition that if(event.target.value > 0): make the statement. But in this case the condition doesn't work.

How can I make it work?

CodePudding user response:

Use if(event.target.value.length === 0)

CodePudding user response:

if the event.target.value is an array

you can use if(event.target.value?.length === 0)

if is an object if(!event.target.value)

CodePudding user response:

else if(event.target.value > 0)
{
    setDisableButton(true);
    setErrorMessageName("Input is empty...");
}

kicks in when the event.target.value is greater than 0 . To check if the value is empty it should be :

else if(event.target.value <= 0)
{
    setDisableButton(true);
    setErrorMessageName("Input is empty...");
}

this will kick in when event.target.value is smaller or equal to zero.

CodePudding user response:

function onChange(event){
    event.persist();
    updateFormState({ ...formState, [event.target.name]: event.target.value});
    if (event.target.name == "llname"){
      setLlnamefield(event.target.value)
      setErrorMessageLlname("")

      const regex = /[a-zA-Z0-9_-]{1,128}/; //for special characters 
      if (regex.test(event.target.value) === false) {
        setErrorMessageName("Max. length: 128 characters. May include numbers, letters, underscore (_), and hyphens (-).");
        setDisableButton(true); 
      }
      else if(event.target.value.trim().split(" ").join().trim().length<=0){
        setDisableButton(true);
        setErrorMessageName("Input is empty...");
      }
    }
  }

const arr = " f    ";
console.log(arr.trim().split(" ").join().trim().length<=0)

  • Related