Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

JavaScript: Validating Letters and Numbers

3.67/5 (2 votes)
30 Apr 2013CPOL2 min read 54.7K  
Validating letters and numbers in JavaScript

Introduction

During web development, almost always, we need to provide input validation on even simple web forms. And in case of web, JavaScript is the best option available for validating input on client-side. Server-side validation has its own important and it should be there but restricting user at the very first step is always needed.

So, in this web development article, I am trying to present some requirement to limit the scope of the article, those are as follows:

  1. Only Numeric Only numeric input should be allowed for some fields. So, the user can’t enter non-numeric characters in those particular fields. One step further, user can’t even copy-paste non-numeric input.
  2. Only Character Limited to alphabetic character input only with an exception, i.e., space character that may require even if we are entering only alphabets. Similarly, copy-paste must be restricted for other characters.
  3. Alphanumeric Alphanumeric input allowed for certain fields but very restricted. A lot of other or special characters shouldn't be allowed.
  4. Email validation Validate against standard email format.

In order to apply these validations, we have a simple "Create User" form having the following fields:

  • User Full Name -> Only alphabet character and space
  • Username -> Only alphabet characters with dot (".") or dash("-")
  • Password -> Anything acceptable
  • Email -> Standard Email format
  • Mobile -> Only numeric input

So, JavaScript functions are explained along with each field for understanding. Let’s take each field one by one with its validation code.

Firstly, User Full Name field that will allow to enter only alphabets and space character. Alphabets can be capital or lower case characters. For example, my son’s complete name will be "Muhammad Ahmad". So, the following field will take input accordingly.

JavaScript
<asp:TextBox ID="txtFullName"
                onkeypress="return ValidateLettersWithSpaceOnly(event);"
                onPaste="return ValidateFullNamePaste(this);"
                MaxLength="50" runat="server">
</asp:TextBox>

JavaScript function validating input is:

JavaScript
function LettersWithSpaceOnly (evt) 
{
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
    ((evt.which) ? evt.which : 0));
    if (charCode > 32 && (charCode < 65 || charCode > 90) &&
        (charCode < 97 || charCode > 122)) {
            return false;
        }
    return true;
}
function ValidateFullNamePaste (obj) 
{
            var totalCharacterCount = window.clipboardData.getData('Text');
            var strValidChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
            var strChar;
            var FilteredChars = "";
            for (i = 0; i < totalCharacterCount.length; i++) {
                strChar = totalCharacterCount.charAt(i);
                if (strValidChars.indexOf(strChar) != -1) {
                    FilteredChars = FilteredChars + strChar;
                }
            }
            obj.value = FilteredChars;
            return false;
}

Secondly, Username/Login field will allow to enter alphabet, dot(".") or dash("-") characters.

JavaScript
<asp:TextBox ID="txtUsername" 
onkeypress="return ValidateUsernameOnly(event);"
              onPaste="return ValidateUsernamePaste(this);" 
MaxLength="30" runat="server">
</asp:TextBox> 
function ValidateUsernameOnly(evt) 
{
            evt = (evt) ? evt : event;
            var characterCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
			((evt.which) ? evt.which : 0));
if (characterCode >

For Email field, a standard email validation is applied but it’s triggered on form submission.

JavaScript
<asp:TextBox ID="txtEmail" 
MaxLength="30" runat="server">
<asp:Button ID="btnSave" Text="Create User" runat="server" 
    OnClientClick="validateEmail(this);" />
function validateEmail(emailField)
 {
            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            if (reg.test(emailField.value) == false) {
                alert('Invalid Email Address');
                return false;
            }
            return true;
        }

And finally, numeric validation for phone number field is as follows:

JavaScript
<asp:TextBox ID="txtPhone" 
onkeypress="return ValidateNumberOnly(event);"
onPaste="return ValidateNumberPaste(this);" 
MaxLength="10" runat="server">
              </asp:TextBox>
function ValidateNumberOnly()
{
if ((event.keyCode < 48 || event.keyCode > 57)) 
{
       event.returnValue = false;
}
}
function ValidateNumberPaste(obj) 
{
            var totalCharacterCount = window.clipboardData.getData('Text');
		    var strValidChars = "0123456789";
            var strChar;
            var FilteredChars = "";
            for (i = 0; i < totalCharacterCount.length; i++) {
                strChar = totalCharacterCount.charAt(i);
                if (strValidChars.indexOf(strChar) != -1) {
                    FilteredChars = FilteredChars + strChar;
                }
            }
            obj.value = FilteredChars;
            return false;
        }

Although this article takes ASP.NET controls as an example, this JavaScript code fully supports standard HTML input controls as well.

Related Web Development Tutorials

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)