Only Character Validation in Javascript for HTML Input TextBox Using Regular Expression

In many cases, we need javascript validation for textbox to allow only alphabets. Most probably it’s the most common validation requirement that HTML & Javascript programmers have performed significantly. Thus I am trying to give you a complete example with the code so that you can perform Only Character Validation in Javascript for HTML Input TextBox Using Regular Expression. We need this javascript validation to allow only alphabets and space in HTML form especially for 2 cases:

Code Example on - only character validation in javascript

  1. How to validate only characters in javascript on onkeypress event
  2. How to validate only characters in javascript on HTML form submission time

I will explain above 2 cases in my own way so that everyone can easily implement HTML input only letters validation very easily.

Only Character Validation in Javascript on onkeypress event

Sometimes we need to do character validation in javascript using regular expression while taking the user input in a HTML Input TextBox control. So that user could not enter any invalid character such as number at entry time. Though we termed this event as onkeypress but you have to use onkeydown event while trying to prevent numeric one or special characters to be entered in the textbox or inputbox.

This sort of javascript validation for textbox to allow only alphabets is basically extremely required for registration form. Because each & every registration form must contain name input field. This is the case where we should consider Only Character Validation in Javascript for HTML Input TextBox Using Regular Expression. To do this, let’s say we have an HTML form like below:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Only Character Validation in Javascript JQuery for HTML Input</title>
</head>
<body>
    <form name="RegistrationForm">
        First Name:&nbsp;&nbsp;<input type="text" name="txtFirstName">
        Last Name:&nbsp;&nbsp;<input type="text" name="txtLastName">
    </form>
</body>
</html>

Now if we want to do Only Character Validation in Javascript for the above HTML Input TextBoxes we have to write a javascript method which will be invoked by the Input TextBoxes onkeydown event. So we need to write the javascript validation function first in the following way:

        function CharacterValidation(ObjTxtControl, CCharacter, sMSG) {
            // Filter out below arrow, delete and backspace keys using keycode
            if ((CCharacter >= 37 && CCharacter <= 40) || CCharacter == 8 || CCharacter == 35 || CCharacter == 36 || CCharacter == 46) {
                // Left arrow / Up arrow/ Right arrow/ Down Arrow, Backspace, End Key, Home key, Delete key
                return;
            }

            if (!/^[a-zA-Z ]*$/g.test(String.fromCharCode(CCharacter))) {//may use regex \b for backspace
                //alert("Invalid character found !");
                ObjTxtControl.focus();
                return false;
            }
        }

Code Explanation to Allow Only Alphabets in Textbox

If you think which keyboard key’s you have to press while entering a name other than characters then obviously those are arrows, backspace, end key, home key & finally delete key. In the above code sample, I have just used the corresponding keycodes to allow along with the character validation regular expression. Moreover in the regular expression I have used a space to allow the space bar. Just it – so simple right! If you don’t required those keys then omit from code.

Validate Only Characters in Javascript on HTML Form Submission Time

The above code example shows how we restrict user to enter a valid name onkeypress event. In this section I will show you how we can perform javascript validation for textbox to allow only alphabets at form submission time once. This is very useful while we are trying to give the user a consolidated error information in one time – form submission time. To do this example you have to develop a Javascript validation function like below:

        function FormCharacterFieldValidation() {

            document.RegistrationForm.txtFirstName.style.backgroundColor = '';
            document.RegistrationForm.txtLastName.style.backgroundColor = '';

            if (document.RegistrationForm.txtFirstName.value == "") {
                alert("First Name Not Found !!");
                document.RegistrationForm.txtFirstName.focus();
                return false;
            }
            if (document.RegistrationForm.txtLastName.value == "") {
                alert("Last Name Not Found !!");
                document.RegistrationForm.txtLastName.focus();
                return false;
            }
            if (!/^[a-zA-Z ]*$/g.test(document.RegistrationForm.txtFirstName.value)) {
                document.RegistrationForm.txtFirstName.style.backgroundColor = 'red';
                //document.RegistrationForm.txtFirstName.focus();
                return false;
            }
            if (!/^[a-zA-Z ]*$/g.test(document.RegistrationForm.txtLastName.value)) {
                document.RegistrationForm.txtLastName.style.backgroundColor = 'red';
                //document.RegistrationForm.txtLastName.focus();
                return false;
            }
        }

And the HTML form should be:

    <form name="RegistrationForm">
        First Name:&nbsp;&nbsp;<input type="text" name="txtFirstName"><br /><br />
        Last Name:&nbsp;&nbsp;<input type="text" name="txtLastName"><br /><br />


        <input type="button" name="cmdCheckName" value="Check Character Validation" onclick="return FormCharacterFieldValidation();">
    </form>

Here while user trying to submit the Registration Form by clicking on the “cmdCheckName” button the user will get red background CSS flag as text field background in runtime in case of failed validation. So that user can understand which input field(s) input needs to fix at a glance. Hope from now & onwards you can apply Only Character Validation in Javascript for HTML Input TextBox Using Regular Expression without taking any help from others.

Complete HTML Code: Javascript Check if String Contains only Letters

Here is the complete HTML code. Tune it as per your need:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Only Character Validation in Javascript JQuery for HTML Input</title>

    <script type="text/javascript">
        function CharacterValidation(ObjTxtControl, CCharacter, sMSG) {
            // Filter out below arrow, delete and backspace keys using keycode
            if ((CCharacter >= 37 && CCharacter <= 40) || CCharacter == 8 || CCharacter == 35 || CCharacter == 36 || CCharacter == 46) {
                // Left arrow / Up arrow/ Right arrow/ Down Arrow, Backspace, End Key, Home key, Delete key
                return;
            }

            if (!/^[a-zA-Z ]*$/g.test(String.fromCharCode(CCharacter))) {//may use regex \b for backspace
                //alert("Invalid character found !");
                ObjTxtControl.focus();
                return false;
            }
        }

        function FormCharacterFieldValidation() {

            document.RegistrationForm.txtFirstName.style.backgroundColor = '';
            document.RegistrationForm.txtLastName.style.backgroundColor = '';

            if (document.RegistrationForm.txtFirstName.value == "") {
                alert("First Name Not Found !!");
                document.RegistrationForm.txtFirstName.focus();
                return false;
            }
            if (document.RegistrationForm.txtLastName.value == "") {
                alert("Last Name Not Found !!");
                document.RegistrationForm.txtLastName.focus();
                return false;
            }
            if (!/^[a-zA-Z ]*$/g.test(document.RegistrationForm.txtFirstName.value)) {
                document.RegistrationForm.txtFirstName.style.backgroundColor = 'red';
                //document.RegistrationForm.txtFirstName.focus();
                return false;
            }
            if (!/^[a-zA-Z ]*$/g.test(document.RegistrationForm.txtLastName.value)) {
                document.RegistrationForm.txtLastName.style.backgroundColor = 'red';
                //document.RegistrationForm.txtLastName.focus();
                return false;
            }
        }
    </script>
</head>
<body>
    <form name="RegistrationForm">
        <!--First Name:&nbsp;&nbsp;<input type="text" name="txtFirstName" onkeydown="return CharacterValidation(this, event.keyCode, 'Enter your first name')"><br /><br />
        Last Name:&nbsp;&nbsp;<input type="text" name="txtLastName" onkeydown="return CharacterValidation(this, event.keyCode, 'Enter your first name')"><br /><br />-->
        First Name:&nbsp;&nbsp;<input type="text" name="txtFirstName"><br /><br />
        Last Name:&nbsp;&nbsp;<input type="text" name="txtLastName"><br /><br />


        <input type="button" name="cmdCheckName" value="Check Character Validation" onclick="return FormCharacterFieldValidation();">
    </form>
</body>
</html>

Still facing problem to implement Only Character Validation in Javascript for HTML Input TextBox Using Regular Expression – please help us to fogure out your problem. Please use our comment section to describe your validation problem with others. Or if you have any other solution please share those with our readers through comment.

HAPPY CODING !!

Posted in Client, Javascript

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code
     
 

*