// Function to validate input
function validateInput(event) {
    // Get the input field and its value
    const inputField = event.target;
    const inputValue = inputField.value;

    // Define the maximum length for input fields
    const maxLength = 255; // Adjust as necessary
    const minLength = 1;    // Minimum length for validation

    // Regular expressions for harmful patterns
    const harmfulPatterns = [
        /<[^>]*>/g,                           // HTML tags
        /on\w+="[^"]*"/gi,                    // Inline event handlers
        /javascript:[^"']*/i,                 // JavaScript URLs
        /(\b(SELECT|INSERT|DELETE|UPDATE|DROP|UNION|WHERE|OR|AND)\b)/i, // SQL injection patterns
        /['"`]/g                              // Quotes
    ];

    // Check length constraints
    if (inputValue.length > maxLength || inputValue.length < minLength) {
        inputField.value = '';
        alert(`Input must be between ${minLength} and ${maxLength} characters.`);
        return;
    }

    // Check for harmful patterns
    for (const pattern of harmfulPatterns) {
        if (pattern.test(inputValue)) {
            inputField.value = '';
            alert("Invalid input detected. Please enter safe text.");
            return; // Exit the function if invalid input is found
        }
    }
}

// Add event listeners to all input fields for real-time validation
window.onload = function () {
    // Select all input fields of specified types
    const inputs = document.querySelectorAll("input[type='text'], input[type='email'], input[type='password']");

    inputs.forEach((input) => {
        // Run validation on input to ensure no invalid input is entered
        input.addEventListener("input", validateInput);
        
        // Run validation on paste to prevent pasted invalid text
        input.addEventListener("paste", (event) => {
            setTimeout(() => validateInput(event), 0);
        });
    });
};
