Search

How to Validate Textbox to Accept only Characters in Javascript

post-title

In this article, we will see how to allow user input text only using Javascript.

Of course, sometimes we want user to input only text character like user name, in this fields numeric or symbol shouldn't be allowed. Same way, we can identify keycode and prevent from typing numeric or symbolic characters.

We can also disable ctrl, alt or shift key using below condition. We can do this like below:

if (e.shiftKey || e.ctrlKey || e.altKey) {
    e.preventDefault();
} else {
    if (!((e.keyCode == 8) || (e.keyCode == 32) || (e.keyCode == 46) || (e.keyCode >= 35 && e.keyCode <= 40) || (e.keyCode >= 65 && e.keyCode <= 90))) {
        // prevent input
        return false;
    } else {
        // allow
    }
}

Here is the full code with error message if user input other key instead of text key:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Only text input textbox</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h1 class="my-3">Only text input textbox</h1>
        <div class="row">
            <div class="col-12">
                <div class="mb-3">
                    <label for="username" class="form-label">Username</label>
                    <input type="text" class="form-control w-50" id="username" placeholder="hackthestuff">
                    <div class="alert alert-danger d-none mt-3 w-50" id="text-message">Only text characters allowed.</div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#username').keydown(function (e) {
                if (e.shiftKey || e.ctrlKey || e.altKey) {
                    e.preventDefault();
                } else {
                    if (!((e.keyCode == 8) || (e.keyCode == 32) || (e.keyCode == 46) || (e.keyCode >= 35 && e.keyCode <= 40) || (e.keyCode >= 65 && e.keyCode <= 90))) {
                        $('#text-message').addClass('d-block').removeClass('d-none');
                        return false;
                    } else {
                        $('#text-message').addClass('d-none').removeClass('d-block');
                    }
                }
            });
        });
    </script>
</body>
</html>

This will create below view and error message when user try to input numeric or symbolic characters.

I hope you liked this article. Thank you for giving time in reading article.