How to Allow only Alphabets in HTML Text Input

Generally, a text input element is used in the HTML forms to accept the user’s input. The user can input alphanumeric and special characters in this text input field. In some specific cases, you are required to allow the user to input only alphabets, and restrict them to input numeric and special characters. In this example code snippet, we will show you how to allow only alpha letters or characters in the input element with HTML.

The following code force input to allow only alphabets in HTML.

HTML <input> element:

<input type="text" name="user_input">

Allow only alphabets:
In the onkeydown event, define the test() method to match the regular expression with the regex pattern for alphabets only.

<input type="text" name="user_input" onkeydown="return /[a-zA-Z]/i.test(event.key)">

Allow only alphanumeric characters:

<input type="text" name="user_input" onkeydown="return /[a-zA-Z0-9]/i.test(event.key)">

Allow only alphanumeric and underscore characters:

<input type="text" name="user_input" onkeydown="return /[a-zA-Z0-9_]/i.test(event.key)">

Leave a reply

keyboard_double_arrow_up