Tuesday, January 13, 2015

Asp.net server controls validation using Javascript client side

Introduction

In this post I will explain how to validate Asp.net server controls using client side Javascript. My previous post 3-Tier Architecture in ASP.Net C# with step by step example, Email id validation using javascript in Asp.net.

Explanation

Asp.net server controls will bind as a HTML controls in browser. Client ID is the variation between a HTML control and a server control.Here why am specifically telling about Client ID is because HTML control ID will be remain same in all pages but Asp.net controls ID will differ in normal page and a master page. So while using the Javascript we have get the control with Client ID. Here I have given how to validate textbox in javascript onkeypress event,Textbox required field validation in javascript, Drop down list required field javascript validation,Checkbox required field validation in javascript, Option button required field validationin javascript.

Please find the below example
var UserFirstName = document.getElementById("<%=txtUserFirstName.ClientID %>");

Now am going to design a User registration screen with Asp.net Server controls and validate the controls with javascript. Why validation is required for a screen, first we are able to avoid junk data and user wrongly entered values.

Design

ur1


<table cellpadding="2" cellspacing="2" border="1" align="center" width="420px">
            <tr align="center">
                <td colspan="2" style="font-size: medium">
                    User Registration
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                    First Name
                </td>
                <td>
                    <asp:TextBox ID="txtFirstName" runat="server" Width="268px" onkeypress="return AllowAlpha(event)"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Last Name
                </td>
                <td>
                    <asp:TextBox ID="txtLastName" runat="server" Width="268px"  onkeypress="return AllowAlpha(event)"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Password
                </td>
                <td>
                    <asp:TextBox ID="txtPassword" runat="server" Width="133px" TextMode="Password"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Confirm Password
                </td>
                <td>
                    <asp:TextBox ID="txtConfirmPassword" runat="server" Width="133px" TextMode="Password"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Gender
                </td>
                <td>
                    <asp:DropDownList ID="ddlGender" CssClass="DropDown" runat="server">
                        <asp:ListItem Text="SELECT" Value="0"></asp:ListItem>
                        <asp:ListItem Text="Male" Value="M"></asp:ListItem>
                        <asp:ListItem Text="Female" Value="F"></asp:ListItem>
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>
                    Marital Status
                </td>
                <td>
                    <asp:RadioButtonList ID="rbtnMaritalStatus" runat="server" RepeatDirection="Horizontal">
                        <asp:ListItem Text="Single" Value="S"></asp:ListItem>
                        <asp:ListItem Text="Married" Value="M"></asp:ListItem>
                    </asp:RadioButtonList>
                </td>
            </tr>
            <tr>
                <td>
                    Contact Email
                </td>
                <td>
                    <asp:TextBox ID="txtContactEmailID" runat="server" Width="270px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Contact Number
                </td>
                <td>
                    <asp:TextBox ID="txtMobileNumber" runat="server" Width="268px"  onkeypress="return AllowInteger(event)"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Address
                </td>
                <td>
                    <asp:TextBox ID="txtAddress" runat="server" Width="272px" Height="60px" TextMode="MultiLine"></asp:TextBox><br />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:CheckBox ID="chkAgree" runat="server" />&nbsp; I Agree with the terms and condition
                    which have mentioned above is correct to my knowledge
                </td>
            </tr>
            <tr align="center">
                <td colspan="2">
                    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click"
                        OnClientClick="return ValidateUser();" />
                </td>
            </tr>
        </table>


Here we have designed a User registration screen with textbox,dropdownlist,radiobutton,checkbox server controls for validation using javascript.Also the data points captured as user firstname,lastname,password,confirm password,gender,marital status,contact email,contact number,address and agree option.

Javascript

<script type="text/javascript">

        function ValidateUser() {

            var message = '';
            //Assign the control values in javascript variables for reuability
            var FirstName = document.getElementById("<%=txtFirstName.ClientID %>");
            var LastName = document.getElementById("<%=txtLastName.ClientID %>");
            var Password = document.getElementById("<%=txtPassword.ClientID %>");
            var ConfirmPassword = document.getElementById("<%=txtConfirmPassword.ClientID %>");
            var Gender = document.getElementById("<%=ddlGender.ClientID %>");
            var ContactEmailID = document.getElementById("<%=txtContactEmailID.ClientID %>");
            var MobileNumber = document.getElementById("<%=txtMobileNumber.ClientID %>");
            var Address = document.getElementById("<%=txtAddress.ClientID %>");
            var Agree = document.getElementById("<%=chkAgree.ClientID %>");
            var MaritalStatus = document.getElementById("<%=rbtnMaritalStatus.ClientID %>");
            var inputsMaritalStatus = MaritalStatus.getElementsByTagName("input");

            if (FirstName == null || FirstName.value == "") {
                message += "\nEnter the First Name.";
            }

            if (LastName == null || LastName.value == "") {
                message += "\nEnter the Last Name.";
            }

            if (Password == null || Password.value == "") {
                message += "\nEnter the Password.";
            }

            if (ConfirmPassword == null || ConfirmPassword.value == "") {
                message += "\nEnter the Confirm Password.";
            }

            if (Gender.selectedIndex <= 0) {
                message += "\nSelect the Gender.";
            }

            var msg = "";
            for (var iLoop = 0; iLoop < inputsMaritalStatus.length; iLoop++) {

                msg = "\nSelect the Marital Status.";
                if (inputsMaritalStatus[iLoop].checked) {
                    msg = "";
                    break;
                }
            }
            if (msg != "") {
                message += msg;
            }

            if (ContactEmailID == null || ContactEmailID.value == "") {
                message += "\nEnter the Contact EmailID.";
            }
            else {
                var eMailValue = ContactEmailID.value;
                var eMailExpression = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
                if (!eMailExpression.test(eMailValue)) {
                    message += "\nEnter valid EmailID.";
                }
            }

            if (MobileNumber == null || MobileNumber.value == "") {
                message += "\nEnter the Mobile Number.";
            }

            if (Address == null || Address.value == "") {
                message += "\nEnter the Address.";
            }

            if (Agree == null || Agree.checked == false) {
                message += "\nCheck the Agree Option.";
            }
            if (ConfirmPassword.value != Password.value) {
                message += "\nPassword and Confirm Password doesn't match.";
            }

            if (message != "") {
                alert("Please Correct the Following\n" + message);
                return false;
            }
            return true;
        }
        function AllowAlpha(e) {

            var allowCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ';
            var keycode = document.all ? parseInt(e.keyCode) : parseInt(e.which);
            return (allowCharacters.indexOf(String.fromCharCode(keycode)) != -1);
        }
        function AllowInteger(e) {

            var keycode = (e.which) ? e.which : e.keyCode;
            if (keycode <= 57 && keycode >= 48) {
                return true;
            }
            return false;
        }
    </script>


In the above Javascipt we are mainly concentrate on required filed validation of all controls, proper email id validation, password and confirm password mismatch, allow only alpha characters with space in first name, last name, allow only numeric characters in mobile number.

Output
 My previous post 3-Tier Architecture in ASP.Net C# with step by step example, Email id validation using javascript in Asp.net.
ur2

4 comments:

Followers