Click here to Skip to main content
15,867,756 members
Articles / Programming Languages / Javascript

JavaScript: Validating Letters and Numbers

Rate me:
Please Sign up or sign in to vote.
3.67/5 (2 votes)
30 Apr 2013CPOL2 min read 54.1K   7   3
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)


Written By
Software Developer (Senior) Emaratech
United Arab Emirates United Arab Emirates
Imran Abdul Ghani has more than 10 years of experience in designing/developing enterprise level applications. He is Microsoft Certified Solution Developer for .NET(MCSD.NET) since 2005. You can reach his blogging at WCF Tutorials, Web Development, SharePoint for Dummies.

Comments and Discussions

 
QuestionI have a query in onpaste event Pin
revathi muthu krishnan25-Jul-14 2:04
revathi muthu krishnan25-Jul-14 2:04 
QuestionGood article to read Pin
Vivek Johari20-Mar-14 19:13
Vivek Johari20-Mar-14 19:13 
GeneralMy vote of 3 Pin
Raju_B5-May-13 19:54
Raju_B5-May-13 19:54 
good one

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.