Monday, 14 April 2014

JavaScript Validation for Letters and Numbers

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 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, 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 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, 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 > 31 && (characterCode < 65 || characterCode > 90) && (characterCode < 45 || characterCode > 46) &&

        (characterCode < 97 || characterCode > 122) && (characterCode < 48 || characterCode > 57)) {

            return false;

        }

        return true;

    }

    function ValidateUsernamePaste(obj) {

        var totalCharacterCount = window.clipboardData.getData('Text');

        var strValidChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.";

        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;

    }
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 as follows.


   <asp:TextBox ID="txtPhone"
    onkeypress="return ValidateNumberOnly(event);"
    onPaste="return ValidateNumberPaste(this);"
    MaxLength="10" runat="server"></asp:TextBox>

  function ValidateNumberOnly(evt)

    {

        if ((evt.keyCode < 48 || evt.keyCode > 57))

        {

            evt.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 but this JavaScript code fully supports standard HTML input controls as well.
Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives