Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 496
mandelbug Avatar asked May 10 '26 11:05

mandelbug


1 Answers

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>
like image 199
Nick Rolando Avatar answered May 13 '26 00:05

Nick Rolando



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!