Select Page

There is a way to use an inline script to do this:

<input type='text' onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode == 32)" placeholder="Only alphabets and space  is allowed"/>

Demo

See the Pen Allow Letters Only by Puneet Sharma (@webdevpuneet) on CodePen.

You can also use it inside a function and call it on multiple text fields. You can choose whichever way suits you best.

HTML

<input type="text" onkeypress="return onlyAlphabets(event,this);" />

JavaScript

function onlyAlphabets(e, t) {
            try {
                if (window.event) {
                    var charCode = window.event.keyCode;
                }
                else if (e) {
                    var charCode = e.which;
                }
                else { return true; }
                if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123 || charCode == 32))
                    return true;
                else
                    return false;
            }
            catch (err) {
                alert(err.Description);
            }
        }

See the Pen Validate / Allow Alphabets and space only in text field by Puneet Sharma (@webdevpuneet) on CodePen.