I wrote a simple script for validating login form as follows:
<script type="text/javascript">
function validateLoginForm(){
var idV = document.forms["LoginForm"]["id"].value;
var pwdV = document.forms["LoginForm"]["pwd"].value;
if (idV == null || idV == "" || idV.length < 5) {
alert("user ID must be filled and of more than 4 characters!!");
id.focus();
return false;
}
if (pwdV == null || pwdV == "" || pwdV.length < 5) {
alert("Password must be filled and of more than 4 characters!!");
pwd.focus();
return false;
}
return true;
}
</script>
and call it as :
<form name="LoginForm" method="POST" onsubmit="return validateLoginForm()" action="Login" >
.
.
.
.
</form>
The problem is that javaScript gives out the alert as i set correctly but in the end the Login
servlet also called automatically, which is a wrong thing..Why this happens? Any solution?
return false cancels the default submit action(stops the submission of form). It means Do nothing . Return the control flow.. It means that do nothing on submit.
The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.
The onsubmit attribute provides the script datas to executed whenever the submit event is occurred so it does not submit the datas to the server with the help of submit() function it will be postponed to the server side.
One way to stop form submission is to return false from your JavaScript function.
Redirect to Login happens because you have js error.
You dont define variable id
and psw
.
So when you try id.focus()
or psw.focus()
- you have js error and return true by default
So add this code:
var id = document.forms["LoginForm"]["id"];
var pwd = document.forms["LoginForm"]["pwd"];
var idV = document.forms["LoginForm"]["id"].value;
var pwdV = document.forms["LoginForm"]["pwd"].value;
Well, strangely enough my form was still submitted even when I returned false
from my function
and returned that function's return to the form's onsubmit
... I even tried:
onsubmit="return false;"
Not sure what was going on... in any case moving the event trigger to the submit
button's onclick
event fixed the problem.
Update: Ended up finding that the code I was editing had another JS handler attached to the onsubmit
event which is why it was ignoring my return false;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With