skip to Main Content

I’m trying to make a function that validates user input and return true if there are no mistakes or false (and display a message) if there is a problem.

If an error found, there is no need to check other inputs, just jump to the end of the function to set and format the error

.

let ValidateInput = function() {

  let errorMessage = "";

  if (input1 == "") {
    errorMessage = "Something";
    continue exithere;
  }

  if (input2 == "") {
    errorMessage = "Something else";
    continue exithere;
  }

  exithere:
  if (errorMessage != "") {
    //Display error
    //Change error <p>'s format by adding classlist
  }
}

Using continue or break shows the error "Jump target cannot cross function boundary .ts(1107)", but my label (exithere:) is inside the function…

I know I can use "return false;" at the end of each if, but I prefer to have only 1 exit point from my function where I can display and format the message just one time, and not at the end of each if statement.

Using break ended with the same error.

2

Answers


  1. You could wrap the whole block of code in a do...while that executes only once and use break to go to the end. But this is much less readable than just returning on invalid input.

    let errorMessage = "";
    do {
      if (input1 == "") {
        errorMessage = "Something";
        break;
      }
    
      if (input2 == "") {
        errorMessage = "Something else";
        break;
      }
    } while (0);
    // break goes to here
    
    Login or Signup to reply.
  2. Another option is looping through each input in a for loop and checking if the value is empty. And adding a data-error attribute to each input field. Then if the value is empty just grabbing that error and breaking the for loop. This will allow you to have dynamic number of fields without having to add more and more to your javascript.

    let validateInput = function() {
    
      let validate = document.querySelectorAll(".validate");
    
      let err = "";
    
      for(let z = 0;z<=validate.length-1;z++){
        let fld = validate[z];
        if(fld.value == ""){
           err = fld.dataset.error;
           break;
        }
    }
    
      if (err != "") {
        err = "Fancy Error: " + err;
      }
      
      return err;
    
    }
    
    document.querySelector("button").addEventListener("click",(e) => {
      console.log(validateInput());
    });
    <input type="text" class="validate" data-error="Please enter in your name">
    <input type="text" class="validate" data-error="Please enter in your Phone">
    <input type="text" class="validate" data-error="Please enter in your Address">
    <hr>
    <button>VALIDATE</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search