Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript jump to label

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

.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading