I have a form that I want to validate looks like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="scripts/validate.js"></script>
</head>
<body>
<form name="frmRegister" method="post" action="register.aspx" onsubmit="return validate(this);">
<div>
<label for="txtUsername">Username:</label>
<input type="text" name="txtUserName" id="txtUserName" size="12" />
</div>
<div>
<label for="txtPassword">Password: </td></label>
<input type="password" name="txtPassword" id="txtPassword" size="12" />
</div>
<div>
<label for="txtPassword2">Confirm your password:</label>
<input type="password" name="txtPassword2" id="txtPassword2" size="12" />
</div>
<div>
<input type="submit" value="Log in" />
</div>
</form>
</body>
</html>
and the validate function in an external file called validate like this:
function validate(form) {
var returnValue = true;
var username = form.txtUserName.value;
var password1 = form.txtPassword.value;
var password2 = form.txtPassword2.value;
if(username.length < 6) {
returnValue = false;
alert("Your username must be at least\n6 characters long.\nPlease try again.");
frmRegister.txtUserName.focus();
}
if (password1.length < 6) {
returnValue = false;
alert("Your password must be at least\n6 characters long.\nPlease try again.");
frmRegister.txtPassword.value = "";
frmRegister.txtPassword2.value = "";
frmRegister.txtPassword.focus();
}
if (password1 != password2) {
returnValue = false;
alert("Your password entries did not match.\nPlease try again.");
frmRegister.txtPassword.value = "";
frmRegister.txtPassword2.value = "";
frmRegister.txtPassword.focus();
}
return returnValue;
}
But Firefox 5 keeps sending it to register.aspx even though the form doesnt pass the test?
You haven’t defined
frmRegister.Internet Explorer will (depending, IIRC, on the version and if you are in quirks mode or not) spew a global variable into existence for every element with an id (and some with a name). Other browsers won’t.
When you try things like:
The browser will error because
frmRegisterisundefinedso can’t have a.txtPassword.When it errors, the script dies and the
returnstatement is never reached.Since
returnis never reached, the submission isn’t canceled, and the form is sent to the server as normal.