Asif
Asif

Reputation: 5038

Why does my HTML form still submit when I return false from onsubmit?

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?

Upvotes: 11

Views: 28781

Answers (6)

Serj Sagan
Serj Sagan

Reputation: 30208

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;

Upvotes: 2

Black
Black

Reputation: 5367

Best practice: if you want to guarantee not to submit the form, even if your Javascript throws en exception, you should wrap your code in try/catch blocks:

<script type="text/javascript">


function validateLoginForm(){
  try{
    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;
    }
 }catch(e){
   console.log(e);
   return false;
 }

return true;
}
</script>

Upvotes: 1

Paul D. Waite
Paul D. Waite

Reputation: 98796

I’ve created a minimal test case here: http://www.pauldwaite.co.uk/test-pages/7723381/

<script>
function pretendValidation(){
    alert("Validatation failed!");
    return false;
}
</script>

<form action="http://www.google.co.uk/" method="POST" onsubmit="return pretendValidation();">
    <input type="submit" value="Submit">
</form>

When I click on “Submit”, the alert happens, and the form does not submit. So in theory, your code should work.

As @Shawty mentioned, you may have a problem with your form HTML. If you post all the HTML as well, we can check that.

Upvotes: 1

shawty
shawty

Reputation: 5829

Without you putting in the entire contents of your form I cannot be sure, but I'm going to take a good guess here. I'm going to say that your tags for your user ID and password fields ONLY have name attributes on them?

When your dealing with forms in HTML, you have to use 'name=' for the parameter names to be passed onto the receiving script. This is what gives your script the ?id=blah&pwd=blah bit in the URL or as the post data payload.

However....

When your accessing values using the DOM (Document object model) as you are in your script, then you need to have the element identified with an 'id=' attribute.

The same holds true for any element anywhere in your doc that you need to access using a scripted approach in js.

If you notice also, you get the alert, but as-well as not returning false, your focus call also never gets called, it will be this that's causing your script to abort as an element called 'id' cannot be found.

add id="id" and id="pwd" next to your name="id" and name="pwd" attributes in your input tags, and you should find that all will work as expected. EG:

    <input type="text" name="id" id="id" ... />

On a last note, I would encourage you however, to re-write this function using something like jQuery, you'll find the model much more intuitive and cross platform friendly.

Upvotes: 1

mymotherland
mymotherland

Reputation: 8228

Try this,

<script type="text/javascript">
    function validateLoginForm(){
    var idV = document.forms["LoginForm"]["id"].value;
    var pwdV = document.forms["LoginForm"]["pwd"].value;
    var err = '';
    if (idV == null || idV == "" || idV.length < 5) {
          err = "user ID must be filled and of more than 4 characters!! \n";
          document.getElementById("id").focus()
    }

    if (pwdV == null || pwdV == "" || pwdV.length < 5) {
        err  = "Password must be filled and of more than 4 characters!! \n";
         document.getElementById("pwd").focus()
    }
    if(err == '')
        return true;
    else
      {
        alert(err);
        return false;
      }
}
</script>

Upvotes: 2

Vasily
Vasily

Reputation: 164

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;

Upvotes: 6

Related Questions