TextBox Validation Client Side And Server Side In ASP.NET WebForm

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.

In this article, we will cover the following.

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

Why do we need validation?

Validation is the main threshold to process the data. We store the textbox value into a database table. Before moving to storing the data into the database, first, we check the value of each textbox.

Example

ASP.NET WebForm

As in the above Form image, we have following fields:

Name, Age, Mobile, Email ID.

I have given a short explanation in the image before moving the form data to a database table.

Other validation :

  • Age > 100 or 125 check if the length is not more than 3 digits.
  • Mobile number length must not be more than 10 digits and less than 10 digits.

Validation is required before accepting the data because, in future, we process and generate the reports as per the received data.

Types of Validation

In web technology, there are two types of validation.

  1. Client Side
  2. Server Side
Client-side Validation

Before validating data in the server, first, we validate it on the client side. User input that is validated in the browser before submitting to the server is called Client-side validation.

Server-side validation

This validation is executed after client-side validation if we have it. But we should or must have server-side validation. A user or hacker can submit the data through different channels also.

Server-side validation comes into the picture/existence while the user submits or posts back.

Client Side Validation Code

We can achieve client side validation with the 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 the following link:

https://en.wikipedia.org/wiki/JavaScript

There are three main functions which validate the Number, Email ID, and entire form fields validator. These functions require textbox object only. Everything else is done by the function itself.

Client Side Number Validator Function

  1. function checkEmail(event) {  
  2.     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,}))$/;  
  3.     if (!re.test(event.value)) {  
  4.         alert("Please enter a valid email address");  
  5.         return false;  
  6.     }  
  7.     return true;  
  8. }  

This function restricts the TextBox to accept only numeric keys. There is no impact on textbox if  other keys are pressed.

You can see that the heart of the 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 details, you can visit this link,

https://www.w3schools.com/jsref/event_key_keycode.asp

Client Side Email Validator Function

  1. function checkEmail(event) {  
  2.     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,}))$/;  
  3.     if (!re.test(event.value)) {  
  4.         alert("Please enter a valid email address");  
  5.         return false;  
  6.     }  
  7.     return true;  

Client Side Email Validator Function

  1. function chkvalidation()  
  2.        {  
  3.            var exitval = false;  
  4.            var rsltcount = 0;  
  5.            var msgtext = "";  
  6.   
  7.            //Age Validation  
  8.            var ageval = document.getElementById("<%= txtAge.ClientID %>").value;  
  9.            var agerslt = false;  
  10.            if (ageval.length > 0)  
  11.            {  
  12.                agerslt = OnlyNumbers(document.getElementById("<%= txtAge.ClientID %>"));  
  13.                if (agerslt == false)  
  14.                {  
  15.                    msgtext = "Invalid age entered.";  
  16.                    rsltcount = 1  
  17.                }  
  18.                else  
  19.                {  
  20.                    if (ageval > 100) {  
  21.                        msgtext = msgtext + "\n Check your entered age.";  
  22.                        rsltcount += 1  
  23.                    }  
  24.                }  
  25.            }  
  26.            else  
  27.            {  
  28.                msgtext =  msgtext + "\n Invalid age or age required.";  
  29.                rsltcount += 1  
  30.            }  
  31.              
  32.            //Mobile Validation  
  33.            var mobileval = document.getElementById("<%= txtMobile.ClientID %>").value;  
  34.            var mobilerslt = false;  
  35.            if (mobileval.length != 10) {  
  36.                msgtext = msgtext + "\n Invalid mobile number or mobile number required";  
  37.                rsltcount += 1  
  38.            }  
  39.            else {  
  40.                mobilerslt = OnlyNumbers(document.getElementById("<%= txtMobile.ClientID %>"));  
  41.                if (mobilerslt == false) {  
  42.                    msgtext = msgtext + "\n Invalid mobile number or mobile number required.";  
  43.                    rsltcount += 1  
  44.                }  
  45.            }  
  46.   
  47.            //Email Validation  
  48.            var emailidval = document.getElementById("<%= txtEmailID.ClientID %>").value;  
  49.            var emailidrslt = false;  
  50.           if (emailidval.length > 1) {  
  51.                    emailidrslt = checkEmail(document.getElementById("<%= txtEmailID.ClientID %>"));  
  52.                if (emailidrslt == false) {  
  53.                    msgtext = msgtext + "\n Invalid email id entered.";  
  54.                    rsltcount += 1  
  55.                }  
  56.            }  
  57.            else {  
  58.               msgtext = msgtext + "\n Email id required.";  
  59.               rsltcount += 1  
  60.            }  
  61.   
  62. if (rsltcount > 0)  
  63.            {  
  64.                exitval = false;  
  65.            }  
  66.            else  
  67.            {  
  68.                exitval = true;  
  69.            }  
  70.              
  71.            alert(msgtext);  
  72.            return exitval;  
  73.            }  

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

ASP.NET WebForm

ASP.NET WebForm

Right click on project title “TextBoxValidateWebForm” --> Select “Add” -->Select “Web Form”.

This will prompt you for file name.

ASP.NET WebForm

Provide a file name such as “myprofile”.

ASP.NET WebForm

After clicking on OK button, you can see your solution explorer which should look like this:

ASP.NET WebForm

In myprofile, we will create a form which has the same fields as in the above image.

  1. Name
  2. Age
  3. Mobile
  4. Email ID

Let's create a tag of the above fields in MYPROFILE.ASPX page.

You page will look like this.

ASP.NET WebForm

Client side blank submission errors:

ASP.NET WebForm

Server side blank submission errors -

ASP.NET WebForm

Code of MyProfile.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="myprofile.aspx.cs" Inherits="myprofile" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8.     <script>  
  9.         function OnlyNumbers(evt) {  
  10.             var charCode = (evt.which) ? evt.which : evt.keyCode;  
  11.             if (charCode != 46 && charCode > 31  
  12.               && (charCode < 48 || charCode > 57))  
  13.                 return false;  
  14.             return true;  
  15.         }  
  16.         function checkEmail(event) {  
  17.             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,}))$/;  
  18.             if (!re.test(event.value)) {  
  19.                 alert("Please enter a valid email address");  
  20.                 return false;  
  21.             }  
  22.             return true;  
  23.         }  
  24.   
  25.         function chkvalidation()  
  26.         {  
  27.             var exitval = false;  
  28.             var rsltcount = 0;  
  29.             var msgtext = "";  
  30.   
  31.             //Age Validation  
  32.             var ageval = document.getElementById("<%= txtAge.ClientID %>").value;  
  33.             var agerslt = false;  
  34.             if (ageval.length > 0)  
  35.             {  
  36.                 agerslt = OnlyNumbers(document.getElementById("<%= txtAge.ClientID %>"));  
  37.                 if (agerslt == false)  
  38.                 {  
  39.                     msgtext = "Invalid age entered.";  
  40.                     rsltcount = 1  
  41.                 }  
  42.                 else  
  43.                 {  
  44.                     if (ageval > 100) {  
  45.                         msgtext = msgtext + "\n Check your entered age.";  
  46.                         rsltcount += 1  
  47.                     }  
  48.                 }  
  49.             }  
  50.             else  
  51.             {  
  52.                 msgtext =  msgtext + "\n Invalid age or age required.";  
  53.                 rsltcount += 1  
  54.             }  
  55.               
  56.             //Mobile Validation  
  57.             var mobileval = document.getElementById("<%= txtMobile.ClientID %>").value;  
  58.             var mobilerslt = false;  
  59.             if (mobileval.length != 10) {  
  60.                 msgtext = msgtext + "\n Invalid mobile number or mobile number required";  
  61.                 rsltcount += 1  
  62.             }  
  63.             else {  
  64.                 mobilerslt = OnlyNumbers(document.getElementById("<%= txtMobile.ClientID %>"));  
  65.                 if (mobilerslt == false) {  
  66.                     msgtext = msgtext + "\n Invalid mobile number or mobile number required.";  
  67.                     rsltcount += 1  
  68.                 }  
  69.             }  
  70.   
  71.             //Email Validation  
  72.             var emailidval = document.getElementById("<%= txtEmailID.ClientID %>").value;  
  73.             var emailidrslt = false;  
  74.            if (emailidval.length > 1) {  
  75.                     emailidrslt = checkEmail(document.getElementById("<%= txtEmailID.ClientID %>"));  
  76.                 if (emailidrslt == false) {  
  77.                     msgtext = msgtext + "\n Invalid email id entered.";  
  78.                     rsltcount += 1  
  79.                 }  
  80.             }  
  81.             else {  
  82.                msgtext = msgtext + "\n Email id required.";  
  83.                rsltcount += 1  
  84.             }  
  85.   
  86.             if (rsltcount > 0)  
  87.             {  
  88.                 exitval = false;  
  89.             }  
  90.             else  
  91.             {  
  92.                 exitval = true;  
  93.             }  
  94.               
  95.             alert(msgtext);  
  96.             return exitval;  
  97.             }  
  98.     </script>  
  99.   
  100. </head>  
  101. <body>  
  102.     <form id="form1" runat="server">  
  103.         <div>  
  104.             <table>  
  105.                 <tr>  
  106.                     <td>Name  
  107.                     </td>  
  108.                     <td>  
  109.                         <asp:TextBox ID="txtName" runat="server" ClientIDMode="Static"></asp:TextBox>  
  110.                     </td>  
  111.                 </tr>  
  112.                 <tr>  
  113.                     <td>Age  
  114.                     </td>  
  115.                     <td>  
  116.                         <asp:TextBox ID="txtAge" runat="server" onkeypress="return OnlyNumbers(event)" MaxLength="3"  ></asp:TextBox>  
  117.                     </td>  
  118.                 </tr>  
  119.                 <tr>  
  120.                     <td>Mobile  
  121.                     </td>  
  122.                     <td>  
  123.                         <asp:TextBox ID="txtMobile" runat="server" MaxLength="10" onkeypress="return OnlyNumbers(event)" ></asp:TextBox>  
  124.                     </td>  
  125.                 </tr>  
  126.                 <tr>  
  127.                     <td>Email ID  
  128.                     </td>  
  129.                     <td>  
  130.                         <asp:TextBox ID="txtEmailID" runat="server" placeholder="yourname@server.com" onblur="checkEmail(this)"></asp:TextBox>  
  131.                     </td>  
  132.                 </tr>  
  133.                 <tr>  
  134.                     <td rowspan="1">  
  135.                         <asp:Button ID="btnSubmit" Text="Submit" runat="server"  OnClick="btnSubmit_Click" OnClientClick="return chkvalidation()" />  
  136.                           
  137.                     </td>  
  138.                 </tr>  
  139.             </table>  
  140.             <asp:Label ID="lblResultMessage" runat="server" Text=""></asp:Label>  
  141.   
  142.   
  143.         </div>  
  144.     </form>  
  145. </body>  
  146. </html>  

Code of MyProfile.aspx.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text.RegularExpressions;  
  5. using System.Web;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8.   
  9. public partial class myprofile : System.Web.UI.Page  
  10. {  
  11.     protected void Page_Load(object sender, EventArgs e)  
  12.     {  
  13.   
  14.     }  
  15.   
  16.     protected void btnSubmit_Click(object sender, EventArgs e)  
  17.     {  
  18.         string MsgText = "";  
  19.         Int32 rsltcount = 0;  
  20.   
  21.   
  22.         //Age Validation  
  23.         bool ageValStatus = VerifyNumericValue(txtAge.Text);  
  24.         if (ageValStatus == false)  
  25.         {  
  26.             rsltcount += 1;  
  27.             MsgText += "Invalid age or age required.</br>";  
  28.         }  
  29.         if (ageValStatus == true)  
  30.         {  
  31.             if(Convert.ToDecimal(txtAge.Text) > 100)  
  32.             {  
  33.                 rsltcount += 1;  
  34.                 MsgText +=  " Check your entered age.</br>";  
  35.             }  
  36.         }  
  37.   
  38.         //Mobile Validation  
  39.         bool mobileValStatus = VerifyNumericValue(txtMobile.Text);  
  40.         if (mobileValStatus == false)  
  41.         {  
  42.             rsltcount += 1;  
  43.             MsgText += "Invalid mobile number or mobile number required.</br>";  
  44.         }  
  45.         if (mobileValStatus == true)  
  46.         {  
  47.             if (txtMobile.Text.Length != 10)  
  48.             {  
  49.                 rsltcount += 1;  
  50.                 MsgText += "Check your entered mobile number.</br>";  
  51.             }  
  52.         }  
  53.   
  54.         //Email ID Validation  
  55.         bool emailidValStatus = VerifyEmailID(txtEmailID.Text);  
  56.         if (emailidValStatus == false)  
  57.         {  
  58.             rsltcount += 1;  
  59.             MsgText += "Invalid email id or email id required.</br>";  
  60.         }  
  61.   
  62.         lblResultMessage.Text = MsgText;  
  63.         lblResultMessage.Font.Bold = false;  
  64.         lblResultMessage.Font.Size = 14;  
  65.         lblResultMessage.ForeColor = System.Drawing.Color.Red;     
  66.   
  67.     }  
  68.   
  69.     public bool VerifyNumericValue(string ValueToCheck)  
  70.     {  
  71.         Int32 numval;  
  72.         bool rslt = false;  
  73.   
  74.         rslt = Int32.TryParse(ValueToCheck, out numval);  
  75.   
  76.         return rslt;  
  77.     }  
  78.   
  79.     public static bool VerifyEmailID(string email)  
  80.     {  
  81.         string expresion;  
  82.         expresion = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";  
  83.         if (Regex.IsMatch(email, expresion))  
  84.         {  
  85.             if (Regex.Replace(email, expresion, string.Empty).Length == 0)  
  86.             {  
  87.                 return true;  
  88.             }  
  89.             else  
  90.             {  
  91.                 return false;  
  92.             }  
  93.         }  
  94.         else  
  95.         {  
  96.             return false;  
  97.         }  
  98.     }  
  99. }