Josh I Josh I - 4 months ago 7
Javascript Question

Creating a "simple" password validation field

I'm trying to make a password field for a webpage. So far I have:

<form name="PasswordField" action="">
Password:
<input type="password" name="password">
<input type="button" value="Log in">
</form>


Pathetic I know. It doesn't have to be fancy, I just need it to "get" the password from the textbox and match it against the password for the page. I'm assuming I can use an if-else?

*Code for get password from textbox when the "Log in" button is pressed here*
if (password = "rawr")
{alert('Correct!')}
else
{alert('Wrong Password')}


Sadly I've been fooling with this for hours. I tried functions, too, and that didn't seem to work (for me) either.

Answer

If you go that route, you need to put the validation inside a function that gets called in the onclick event of your button. Also to access the password <input node in js, you can give it an id and use document.getElementById(id). Also, = is an assignment operator. Use == for comparison :)

<head>
<script type="text/javascript">
function isValid(){
var password = document.getElementById('password').value;
if (password == "rawr")
{alert('Correct!')}
else
{alert('Wrong Password')}
}
</script>
</head>

<form name="PasswordField" action="">
Password:
<input type="password" id="password" name="password">
<input type="button" value="Log in" onclick="isValid();">
</form>

Or an even easier way would be to pass the password DOM node as an argument to the function:

<head>
<script type="text/javascript">
function isValid(myNode){
var password = myNode.value;
if (password == "rawr")
{alert('Correct!')}
else
{alert('Wrong Password')}
}
</script>
</head>

<form name="PasswordField" action="">
Password:
<input type="password" id="password" name="password">
<input type="button" value="Log in" onclick="isValid(this);">
</form>