Password Matching using JavaScript
Last Updated :
30 Sep, 2024
Improve
In an online application form or social media signup page, it’s common to have two input fields: one for the password and another for confirming the password. The goal is to check whether the entered passwords match.
To achieve this, the first password is stored in a variable password1, and the confirmation password is stored in password2. We then compare the values of these two variables. If both values are equal, it indicates that the passwords match; otherwise, it means they do not match.
This is a simple and effective way to ensure the user has entered the same password in both fields.
Example: Below is the implementation of the above approach:
<!DOCTYPE html>
<html>
<head>
<style>
.gfg {
font-size: 40px;
color: green;
font-weight: bold;
text-align: center;
}
.geeks {
font-size: 17px;
text-align: center;
margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="gfg">GeeksforGeeks</div>
<div class="geeks">A computer science portal for geeks</div>
<form onSubmit="return checkPassword(this)">
<table border=1 align="center">
<tr>
<!-- Enter Username -->
<td>Username:</td>
<td><input type=text name=name size=25</td>
</tr>
<tr>
<!-- Enter Password. -->
<td>Password:</td>
<td><input type=password name=password1 size=25</td>
</tr>
<tr>
<!-- To Confirm Password. -->
<td>Confirm Password:</td>
<td><input type=password name=password2 size=25></td>
</tr>
<tr>
<td colspan=2 align=right>
<input type=submit value="Submit">
</td>
</tr>
</table>
</form>
<script>
// Function to check Whether both passwords
// is same or not.
function checkPassword(form) {
password1 = form.password1.value;
password2 = form.password2.value;
// If password not entered
if (password1 == '')
alert("Please enter Password");
// If confirm password not entered
else if (password2 == '')
alert("Please enter confirm password");
// If Not same return False.
else if (password1 != password2) {
alert("\nPassword did not match: Please try again...")
return false;
}
// If same return True.
else {
alert("Password Match: Welcome to GeeksforGeeks!")
return true;
}
}
</script>
</body>
</html>
Output:
Video Player
00:00
00:00