''Error: A 'return' statement can only be used within a function body' - HTML Form
I am getting an error in my old HTML form onsubmit return statement. It was working perfectly fine before but recently the same statement is showing an error. I am attaching the screenshot of the error HTML form return statement error
<form action="index.html" onsubmit = 'return validate();'>
- Error: A 'return' statement can only be used within a function body.*
I have tried removing 'return' but the form gets submitted even if the validate function returns false.
Then I added preventDefault(), but now the form doesn't get submitted or redirected even if the validate function returns true.
<form action="index.html" onsubmit = ' preventDefault() validate();'>
JS code
function validate() {
if (em.value.trim() == "" || pas.value.trim() == "") {
alert("Fields not filled");
em.style.border = "2px solid red";
pas.style.border = "2px solid red";
return false;
}
else if (regexp.test(em.value)) {
er.innerHTML = "VALID!";
er.style.color = "green";
return true;
}
else {
er.innerHTML = "INVALID E-MAIL!!"; //!Alert this is important line
er.style.color = "red";
em.style.border = "2px solid red";
return false;
}
}
Solution 1:[1]
If I'm understanding you correctly, you are referring to a trick to use return false; to prevent a form from submitting. See here and here.
As of February 16, it seems that vscode has been throwing an error on the return false;. However, the code still works, even if vscode says there is an error. Therefore it might be best just to ignore vscode's error message.
There is a github issue currently open on vscode mentioning the new behavior change. The github issue also has a guide on disabling errors with vscode. Specifically, I followed tjx666's comment to disable the error squiggles.
Solution 2:[2]
Just remove the return for example: onsubmit="verif();" in your case: onsubmit = 'validate();'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | phlaxyr |
| Solution 2 | yosr C'h |
