user1554726
user1554726

Reputation: 39

Form submits even if validation fails

I'm just learning Javascript, so bear with me if my question seems silly...

I need to create an html form and run some validation on the fields. Regardless of whether the fields are correctly filled or not, I get an error 404 when hitting the submit button. If I copy/paste someone else's code that does the same thing, it works fine. The file "somepage.php" does not exist, but neither does it for the other person's code.

I coded it in CodeLobster, then in Notepad++. No change.

Here's the HTML file, and further down is the content of the javascript file...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>

    <head>
        <title>Registration Form</title>
        <script type="text/javascript" src="js.js"></script>
    </head>

    <body>
        <form action="somepage.php" onsubmit="checkLogin()" method="post" >

                Name: <input type="text" name="name" id="nameF" /><br />
                Email: <input type="text" name="email" id="emailF" /><br />

            <input type="submit" value="Submit" name="submit" />    

        </form>
    </body>

</html>

function checkLogin()
{
   var emailPattern = /^\w+([\.\-]?\w+)*@\w+([\.\-]?\w+)*\.[a-z]{2,6}$/i;
   var email = document.getElementById('emailF').value;
   var name = document.getElementById('name').value;    

    if (email == "")
    {
        alert("Please enter valid email address.");
       document.getElementById('emailF').select();
        document.getElementById('emailF').focus();
       return false;
    } else if   (name == "") {
        alert("Please enter your name.");
       document.getElementById('nameF').select();
        document.getElementById('nameF').focus();
       return false;
    }  else if (!emailPattern.test(email)) {
        alert("The email address entered is invalid");
       document.getElementById('emailF').select();
        document.getElementById('emailF').focus();
       return false;
    }
    return true;    
}

Upvotes: 1

Views: 4890

Answers (1)

Hamish
Hamish

Reputation: 23316

Your problem is not that the page is missing (you know that already). The problem is your form submits anyway, even if validation fails.

The form.onsubmit method should return false to prevent the form submitting. In other words, this:

<form action="somepage.php" onsubmit="checkLogin()" method="post" >

Should be:

<form action="somepage.php" onsubmit="return checkLogin()" method="post" >

Of course, if the form does validate, it will correctly proceed to somepage.php at which point you will expect to get a 404 error as the page doesn't exist.

Upvotes: 5

Related Questions