DEV Community

Ben Santora
Ben Santora

Posted on

Password Checker - JavaScript

This program opens a window in the browser. User inputs a password its level of strength. It runs from a single .html file containing 72 lines of code, including both the HTML structure and embedded JavaScript for functionality.

This example is for the purpose of teaching how to code. The program is basic and provides a simple, rule-based password strength check. It should be considered a preliminary tool, not a comprehensive security measure.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Password Strength Checker</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: flex-start; /* Align the container at the top */
            height: 100vh;
            margin: 0;
            background-color: #f4f4f4;
        }

        .container {
            text-align: center;
            background-color: white;
            padding: 10px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            width: 220px; /* Small width similar to audio player */
            height: auto; /* Let height adjust based on content */
            margin-top: 20vh; /* Moves the container down by 20% of the viewport height */
        }

        input[type="password"] {
            padding: 5px;
            width: 180px; /* Keep it small */
            margin-top: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        #strength {
            margin-top: 10px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Password Checker</h1>
        <input type="password" id="password" placeholder="Enter password">
        <div id="strength">Strength: </div>
    </div>

    <script>
        const passwordInput = document.getElementById('password');
        const strengthDisplay = document.getElementById('strength');

        passwordInput.addEventListener('input', function() {
            const password = passwordInput.value;
            const strength = calculatePasswordStrength(password);
            strengthDisplay.textContent = `Strength: ${strength}`;
        });

        function calculatePasswordStrength(password) {
            let strength = 'Weak';
            if (password.length >= 8) {
                strength = 'Medium';
            }
            if (/[A-Z]/.test(password) && /[0-9]/.test(password) && /[^A-Za-z0-9]/.test(password)) {
                strength = 'Strong';
            }
            return strength;
        }
    </script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Ben Santora - October 2024

Top comments (0)