Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

JavaScript: Validating Letters and Numbers

, 30 Apr 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

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

JavaScript function validating input is:

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.

<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.

<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:

<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)

Share

About the Author

Imran Abdul Ghani
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.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionI have a query in onpaste event Pinmemberrevathi muthu krishnan25-Jul-14 3:04 
QuestionGood article to read PinmemberVivek Johari20-Mar-14 20:13 
GeneralMy vote of 3 PinmemberKamarajub5-May-13 20:54 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141220.1 | Last Updated 30 Apr 2013
Article Copyright 2013 by Imran Abdul Ghani
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid