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
You could wrap the whole block of code in a
do...while
that executes only once and usebreak
to go to the end. But this is much less readable than just returning on invalid input.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.