Skip to content

Instantly share code, notes, and snippets.

@jared201
Created July 23, 2024 01:56
Show Gist options
  • Save jared201/36d3b6eb9d2f0ebedccce310d4b36b51 to your computer and use it in GitHub Desktop.
Save jared201/36d3b6eb9d2f0ebedccce310d4b36b51 to your computer and use it in GitHub Desktop.
Form validation on keystroke
<!DOCTYPE html>
<html>
<head>
<title>Alphanumeric Input Validation</title>
<script>
document.addEventListener("DOMContentLoaded", function() {
var inputField = document.getElementById("alphanumericInput");
inputField.addEventListener("keypress", function(event) {
var regex = /^[a-zA-Z0-9]+$/;
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
});
</script>
</head>
<body>
<form>
<label for="alphanumericInput">Enter Alphanumeric Characters:</label>
<input type="text" id="alphanumericInput" name="alphanumericInput">
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment