How to validate confirm password using JavaScript ?
To validate confirm password using JavaScript, you can follow these steps:
- Get the values of the password and confirm password fields using
document.getElementById()
. - Compare the values of the two fields.
- If the values match, return
true
to indicate that the form is valid. If the values do not match, returnfalse
to indicate that the form is invalid. - You can also display an error message if the passwords do not match.
Here's an example code snippet:
<form>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<label for="confirm-password">Confirm Password:</label>
<input type="password" id="confirm-password" name="confirm-password"><br><br>
<button type="submit" onclick="return validateForm()">Submit</button>
</form>
<script>
function validateForm() {
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirm-password").value;
if (password != confirmPassword) {
alert("Passwords do not match.");
return false;
}
return true;
}
</script>
In this example, the validateForm()
function is called when the user clicks the submit button. The function gets the values of the password and confirm password fields and compares them. If the passwords do not match, an error message is displayed and the function returns false
to prevent the form from being submitted. If the passwords match, the function returns true
to allow the form to be submitted.