âš ī¸ Warning âš ī¸ Deprecated Code! This video tutorial contains outdated code.
💡 If you wish to update it, any AI assistant will update the code for you in seconds.

Restrict Text Input Characters HTML JavaScript Tutorial

Published : December 16, 2015   •   Last Edited : November 24, 2025   •   Author : Adam Khoury

Learn to restrict one or more text fields in a form to allow only characters that you desire to be typed into them. We will remove undesirable characters in real time as the user types.

<script>
function lettersOnly(input) {
    var regex = /[^a-z]/gi;
    input.value = input.value.replace(regex, "");
}
</script>
<input id="firstname" placeholder="first name" onkeyup="lettersOnly(this)">
<input id="lastname" placeholder="last name" onkeyup="lettersOnly(this)">