PDA

View Full Version : Password confirmation (JavaScript)


Kalessin
02-24-2004, 07:50 AM
Hi :)

I'm having a problem with a form that requires various items of user data, culminating in a request for a password.

The password has to be entered twice, of course, then it executes a password checker on submit:


function checkPasswords() {
if (document.newuser.password.value!=document.newuser.pwdconf.value) {
alert('Passwords do not match');
document.newuser.password.value='';
document.newuser.pwdconf.value='';
document.newuser.password.focus();
return false;
} else {
return true;
}
}

The form itself looks like this:


<form name="newuser" id="newuser" method="post" action="<?php echo $PHP_SELF?>" onsubmit="checkPasswords();">
<p>Add new User</p>
<table width="300" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>User ID</td>
<td><input name="user_id" type="text" maxlength="4" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name" onblur="setInitials();" /></td>
</tr>
<tr>
<td>Initials</td>
<td><input type="text" name="initials" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="password" name="pwdconf" /></td>
</tr>
</table>
<p>
<input type="submit" name="Submit" value="Submit" />
</p>
</form>

The problem is, when I enter test data, including two deliberately mismatched passwords, the alert box pos up as expected, the two password fields are cleared, the cursor focuses on the first password field... and then the form submits anyway.

The action="<?php echo $PHP_SELF?>" bit is because the php script that handles the form is in the same page, and just detects whether the form has been submitted, or if this is the page loading for the first time. Is that the problem? I don't want to have to do it in two pages...

Cheers,

Kal

agent002
02-24-2004, 08:33 AM
Your function returns true/false, but that doesn't still tell anything to the form. You will need to return the form the return value of the function... might sound complicated, but the only thing you need to do is:
<form name="newuser" id="newuser" method="post" action="<?php echo $PHP_SELF?>" onsubmit="return checkPasswords();">
BTW, I hope your PHP also checks that the passwords match, because the JavaScript you use is not a secure method, it is just time saving for anybody who has JavaScript enabled in his browser.

Kalessin
02-25-2004, 03:28 AM
That's great, thanks. Can't believe I missed something so elementary.

My php does not check the passwords, but this will be run on only one machine on an intranet, which will have JavaScript enabled, so I don't give a toss :)