JSFiddle - React, Tailwind, and code Playground

by Vetrivel Samidurai

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Validation</title>
</head>
<body>

<form id="myForm">
    <label for="inputField">Enter Alphanumeric and Underscore:</label>
    <input type="text" id="inputField" name="inputField" oninput="validateInput(this)">
    <br>
    <input type="submit" value="Submit">
</form>

<script>

</script>

</body>
</html>

JavaScript

function validateInput(inputField) {
        // Allow alphanumeric characters and underscores
        var allowedCharacters = /^[a-zA-Z0-9_]+$/;

        // Get the input value
        var inputValue = inputField.value;

        // Check if the input value contains any disallowed characters
        if (!allowedCharacters.test(inputValue)) {
            // Remove disallowed characters
            inputField.value = inputValue.replace(/[^a-zA-Z0-9_]/g, '');
        }
        
        
          var inputField = document.getElementById("inputField").value;

        // Define the regular expression pattern
        var pattern = /^[a-zA-Z0-9_]+$/;

        // Test the input against the pattern
        if (!pattern.test(inputField)) {
            // Show error message in an alert box
            alert("Only alphanumeric characters and underscores are allowed.");
            event.preventDefault(); // Prevent the form from submitting
        }
    }