How to Validate Textbox to Accept only Characters in Javascript

  1870 views   7 months ago Javascript

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/[email protected]/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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]