Search Your Dot Net Topic

Monday 2 October 2017

TextBox Clientside and Serverside Validation in Asp.Net WebForm

TextBox Validation Client side and Server side in Asp.Net WebForm

Why we need validation?
Types of Validation : Client Side and Server Side
Client Side Validation Code
Server Side Validation Code
Validation in WebForm


Why we need validation?
Validation is main thing to process the data. We store the textbox value into database table. Before moving to storing and storing data into database first we check the value of each textbox.

Example:
TextBox Clientside and Serverside Validation in Asp.Net WebForm,  Email Validation and Numeric Validation
TextBox Clientside and Serverside Validation in Asp.Net WebForm,  Email Validation and Numeric Validation


As above Form image shown, We have following fields:
Name, Age, Mobile, Email ID.

I had given short explanation in image before moving form data to database table.

Other validation following like:
1.Age > 100 or 125 check or length not more than 3 digit.
2.Mobile number length not more than 10 digit and less than 10 digit.

Conclusion is validation required before accepting data because in future process and generate the reports as per received datas.


In next page you come to know about TYPES OF VALIDATION

Types of Validation:
In web technology there are two types of validations:
1. Client Side
2. Server Side

1. Client Side Validation: Before validating data in server , first we validate in client side. User inputs validation in user browser level before submitting to server is called Client side validation.

2.Server side validation: This validation executing after client side validation if we have. But we should or must have server side validation. User or hacker can submit data through different channels also.

Server side validation come into picture/existence while user submit or post back happened.




Client Side Validation Code
We can achieve client side validation with help of following:
1. JavaScript
2. Jquery

In this article I had used JavaScript to validate the TEXTBOX. To know more about JavaScript please visit following link:

There are three main functions which validate the Number, Email ID and entire form fields validator. These functions required textbox object rest of thing done by function itself.


Client Side Number Validator Function:

        function OnlyNumbers(evt) {
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if (charCode != 46 && charCode > 31
              && (charCode < 48 || charCode > 57))
                return false;
            return true;
        }

Function restrict the TextBox to accept only numeric keys. There is no impact on textbox of other keys pressed.

You can see heart of above code is charCode and charCode is nothing but a keyCode. keyCode is property of the pressed keyboard key. Every key having there own keycode, like Ascii
A - 65, B - 66.

For more detail you can visit this link:


Client Side Email Validator Function:

        function checkEmail(event) {
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            if (!re.test(event.value)) {
                alert("Please enter a valid email address");
                return false;
            }
            return true;
        }


Client Side Form Fields Validator Function:
 function chkvalidation()
        {
            var exitval = false;
            var rsltcount = 0;
            var msgtext = "";

            //Age Validation
            var ageval = document.getElementById("<%= txtAge.ClientID %>").value;
            var agerslt = false;
            if (ageval.length > 0)
            {
                agerslt = OnlyNumbers(document.getElementById("<%= txtAge.ClientID %>"));
                if (agerslt == false)
                {
                    msgtext = "Invalid age entered.";
                    rsltcount = 1
                }
                else
                {
                    if (ageval > 100) {
                        msgtext = msgtext + "\n Check your entered age.";
                        rsltcount += 1
                    }
                }
            }
            else
            {
                msgtext =  msgtext + "\n Invalid age or age required.";
                rsltcount += 1
            }
            
            //Mobile Validation
            var mobileval = document.getElementById("<%= txtMobile.ClientID %>").value;
            var mobilerslt = false;
            if (mobileval.length != 10) {
                msgtext = msgtext + "\n Invalid mobile number or mobile number required";
                rsltcount += 1
            }
            else {
                mobilerslt = OnlyNumbers(document.getElementById("<%= txtMobile.ClientID %>"));
                if (mobilerslt == false) {
                    msgtext = msgtext + "\n Invalid mobile number or mobile number required.";
                    rsltcount += 1
                }
            }

            //Email Validation
            var emailidval = document.getElementById("<%= txtEmailID.ClientID %>").value;
            var emailidrslt = false;
           if (emailidval.length > 1) {
                    emailidrslt = checkEmail(document.getElementById("<%= txtEmailID.ClientID %>"));
                if (emailidrslt == false) {
                    msgtext = msgtext + "\n Invalid email id entered.";
                    rsltcount += 1
                }
            }
            else {
               msgtext = msgtext + "\n Email id required.";
               rsltcount += 1
            }

 if (rsltcount > 0)
            {
                exitval = false;
            }
            else
            {
                exitval = true;
            }
            
            alert(msgtext);
            return exitval;
            }


Above function for to validate Age, Mobile and Email text-box of the form.




TextBox Clientside and Serverside Validation in Asp.Net WebForm,  Email Validation and Numeric Validation
TextBox Clientside and Serverside Validation in Asp.Net WebForm,  Email Validation and Numeric Validation
3. 


TextBox Clientside and Serverside Validation in Asp.Net WebForm,  Email Validation and Numeric Validation
Add new WebForm



Right click on project title “TextBoxValidateWebForm” --> Select “Add” -->Select “Web Form”
This will prompt you for file name.

TextBox Clientside and Serverside Validation in Asp.Net WebForm,  Email Validation and Numeric Validation
Add new aspx page


Provide a file name “myprofile”.

TextBox Clientside and Serverside Validation in Asp.Net WebForm,  Email Validation and Numeric Validation
Change the default name to myprofile



After clicking on OK button you can see your solution explorer should look like this:
TextBox Clientside and Serverside Validation in Asp.Net WebForm,  Email Validation and Numeric Validation
TextBox Validation Solution Explorer


In myprofile we will create a form which having same fields as in above image.
1. Name
2. Age
3. Mobile
4. Email ID
Lets create a tag of above fields in MYPROFILE.ASPX page.

You page look like this:
TextBox Clientside and Serverside Validation in Asp.Net WebForm,  Email Validation and Numeric Validation
Page will display like this



Client side blank submission errors:
TextBox Clientside and Serverside Validation in Asp.Net WebForm,  Email Validation and Numeric Validation
Client Side Text Box Validation Errors



Server side blank submission errors:
TextBox Clientside and Serverside Validation in Asp.Net WebForm,  Email Validation and Numeric Validation
Server Side Validation Errors




Code of MyProfile.aspx 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="myprofile.aspx.cs" Inherits="myprofile" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script>
        function OnlyNumbers(evt) {
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if (charCode != 46 && charCode > 31
              && (charCode < 48 || charCode > 57))
                return false;
            return true;
        }
        function checkEmail(event) {
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            if (!re.test(event.value)) {
                alert("Please enter a valid email address");
                return false;
            }
            return true;
        }

        function chkvalidation()
        {
            var exitval = false;
            var rsltcount = 0;
            var msgtext = "";

            //Age Validation
            var ageval = document.getElementById("<%= txtAge.ClientID %>").value;
            var agerslt = false;
            if (ageval.length > 0)
            {
                agerslt = OnlyNumbers(document.getElementById("<%= txtAge.ClientID %>"));
                if (agerslt == false)
                {
                    msgtext = "Invalid age entered.";
                    rsltcount = 1
                }
                else
                {
                    if (ageval > 100) {
                        msgtext = msgtext + "\n Check your entered age.";
                        rsltcount += 1
                    }
                }
            }
            else
            {
                msgtext =  msgtext + "\n Invalid age or age required.";
                rsltcount += 1
            }
            
            //Mobile Validation
            var mobileval = document.getElementById("<%= txtMobile.ClientID %>").value;
            var mobilerslt = false;
            if (mobileval.length != 10) {
                msgtext = msgtext + "\n Invalid mobile number or mobile number required";
                rsltcount += 1
            }
            else {
                mobilerslt = OnlyNumbers(document.getElementById("<%= txtMobile.ClientID %>"));
                if (mobilerslt == false) {
                    msgtext = msgtext + "\n Invalid mobile number or mobile number required.";
                    rsltcount += 1
                }
            }

            //Email Validation
            var emailidval = document.getElementById("<%= txtEmailID.ClientID %>").value;
            var emailidrslt = false;
           if (emailidval.length > 1) {
                    emailidrslt = checkEmail(document.getElementById("<%= txtEmailID.ClientID %>"));
                if (emailidrslt == false) {
                    msgtext = msgtext + "\n Invalid email id entered.";
                    rsltcount += 1
                }
            }
            else {
               msgtext = msgtext + "\n Email id required.";
               rsltcount += 1
            }

            if (rsltcount > 0)
            {
                exitval = false;
            }
            else
            {
                exitval = true;
            }
            
            alert(msgtext);
            return exitval;
            }
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Name
                    </td>
                    <td>
                        <asp:TextBox ID="txtName" runat="server" ClientIDMode="Static"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Age
                    </td>
                    <td>
                        <asp:TextBox ID="txtAge" runat="server" onkeypress="return OnlyNumbers(event)" MaxLength="3"  ></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Mobile
                    </td>
                    <td>
                        <asp:TextBox ID="txtMobile" runat="server" MaxLength="10" onkeypress="return OnlyNumbers(event)" ></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Email ID
                    </td>
                    <td>
                        <asp:TextBox ID="txtEmailID" runat="server" placeholder="yourname@server.com" onblur="checkEmail(this)"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td rowspan="1">
                        <asp:Button ID="btnSubmit" Text="Submit" runat="server"  OnClick="btnSubmit_Click" OnClientClick="return chkvalidation()" />
                        
                    </td>
                </tr>
            </table>
            <asp:Label ID="lblResultMessage" runat="server" Text=""></asp:Label>


        </div>
    </form>
</body>
</html>




Code of MyProfile.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class myprofile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string MsgText = "";
        Int32 rsltcount = 0;


        //Age Validation
        bool ageValStatus = VerifyNumericValue(txtAge.Text);
        if (ageValStatus == false)
        {
            rsltcount += 1;
            MsgText += "Invalid age or age required.</br>";
        }
        if (ageValStatus == true)
        {
            if(Convert.ToDecimal(txtAge.Text) > 100)
            {
                rsltcount += 1;
                MsgText +=  " Check your entered age.</br>";
            }
        }

        //Mobile Validation
        bool mobileValStatus = VerifyNumericValue(txtMobile.Text);
        if (mobileValStatus == false)
        {
            rsltcount += 1;
            MsgText += "Invalid mobile number or mobile number required.</br>";
        }
        if (mobileValStatus == true)
        {
            if (txtMobile.Text.Length != 10)
            {
                rsltcount += 1;
                MsgText += "Check your entered mobile number.</br>";
            }
        }

        //Email ID Validation
        bool emailidValStatus = VerifyEmailID(txtEmailID.Text);
        if (emailidValStatus == false)
        {
            rsltcount += 1;
            MsgText += "Invalid email id or email id required.</br>";
        }

        lblResultMessage.Text = MsgText;
        lblResultMessage.Font.Bold = false;
        lblResultMessage.Font.Size = 14;
        lblResultMessage.ForeColor = System.Drawing.Color.Red;   

    }

    public bool VerifyNumericValue(string ValueToCheck)
    {
        Int32 numval;
        bool rslt = false;

        rslt = Int32.TryParse(ValueToCheck, out numval);

        return rslt;
    }

    public static bool VerifyEmailID(string email)
    {
        string expresion;
        expresion = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
        if (Regex.IsMatch(email, expresion))
        {
            if (Regex.Replace(email, expresion, string.Empty).Length == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
}