Validate a password using HTML and JavaScript
Last Updated :
30 Sep, 2024
Improve
Validating a password using HTML and JavaScript involves ensuring that user-entered passwords meet certain criteria, such as length, complexity, or character types (e.g., uppercase, lowercase, numbers, and symbols). This process enhances security by enforcing strong password requirements before form submission.
A password is correct if it contains:
- At least 1 uppercase character.
- At least 1 lowercase character.
- At least 1 digit.
- At least 1 special character.
- Minimum 8 characters.
Approach :
- Retrieve Input Value: The test_str() function retrieves the value from the input field with id="t1" using document.getElementById().
- Check Password Criteria: Regular expressions are used to check for lowercase, uppercase, digits, special characters, and minimum length of 8 characters.
- Set Validation Result: If all conditions are met, the result is set to "TRUE"; otherwise, it is set to "FALSE".
- Display Output: The result is displayed in a readonly input field with id="t2", showing whether the password is valid or not.
Example: In this example we are following above-explained approach.
<!DOCTYPE html>
<html>
<head>
<title>validate password</title>
<script type="text/javascript">
function test_str() {
let res;
let str =
document.getElementById("t1").value;
if (str.match(/[a-z]/g) && str.match(
/[A-Z]/g) && str.match(
/[0-9]/g) && str.match(
/[^a-zA-Z\d]/g) && str.length >= 8)
res = "TRUE";
else
res = "FALSE";
document.getElementById("t2").value = res;
}
</script>
</head>
<body>
<p>
String:
<input type="text" placeholder="abc" id="t1" />
<br />
<br />
<input type="button" value="Check" onclick="test_str()" />
<br />
<br /> Output:
<input type="text" id="t2" readonly />
</p>
</body>
</html>
Output:
