I created a simple HTML form which takes input as username of the customer. It validates if it is indeed a valid username or not. If yes then it should go to the step2.php page if not then it should display an error and stay on the original page.
Here is my HTML code:
<form method="post" onsubmit="validateUsername();" id="myform" name="myform" action="step2.php">
Choose username: <input type="text" id="username" name="username" />
<input type="submit" value="Submit">
</form>
I am validating username by using a javascript function:
function validateUsername()
{
var x=document.forms["myform"]["username"].value.length;
if (x < 5)
{
alert('Username too short.');
return false;
}
else
{
return true;
}
}
My problem:
If the user enters a short username then it displays an alert message “Username too short”. When I press “OK” button on alert message then it is going to step2.php. Ideally it should send data to step2.php only when username is validated correctly. But this is not happening.
Anyone able to find the bug in my code?
Change:
To:
Note the addition of the keyword
returnwhich should cancel the form from submitting ifvalidateUsernamereturns false.