JavaScript Validation Using Key Code And Regular Expression In ASP.NET

Using a JavaScript function, we can validate a field in our ASP.NET page. In this blog, let us see how to do that.

Sometimes, we need to validate user input before or after they enter the value in a textbox or any other control on a page. At that time, we can check the below conditions. 
 
Below are some sample conditions with functions and Key Code and Regular Expression respectively. 
 
Let's start with the Key Code first.
 
Key Code
 
Suppose, we have a condition that we have allowed only Characters and Tab. 
  1. <asp:TextBox ID="txtname" Width="200px" runat="server" MaxLength="250"   
  2. onkeyup="Javascript:
     IsCharacter
    ();"
     Style="max-width: 200px; max-height: 80px; min-width: 200px; min-height: 80px;" onkeypress="return IsCharacterNumber(event,this.value.length <= 250);"></asp:TextBox>    
     
  1. function IsCharacter(e) {  
  2.    var charCode = (e.which) ? e.which : e.keyCode;  
  3.    if (!(charCode >= 65 && charCode <= 90) && !(charCode >= 97 && charCode <= 122) && (charCode != 32 && charCode != 8) && !(charCode == 9)) {  
  4.    return false;  
  5.    }  
  6. return true;  
  7. }  
When we have a condition that we have allowed only an IP Address.
  1. function IsCheckIP(e) {  
  2. var charCode = (e.which) ? e.which : e.keyCode;  
  3. if (charCode != 58 && charCode != 47 && charCode != 46 && (!(charCode >= 65 && charCode <= 90)) && (!(charCode >= 97 && charCode <= 122)) && (!(charCode >= 48 && charCode <= 57)) && (charCode != 8) && !(charCode == 9)) {  
  4.       return false;  
  5.    }  
  6. return true;  
  7. }  
When you have allowed only Numeric values and Tab.
  1. function Numeric(e) {  
  2.    var charCode = (e.which) ? e.which : e.keyCode;  
  3.    if (!(charCode >= 48 && charCode <= 57) && !(charCode == 9)) {  
  4.       return false;  
  5.       }  
  6.    return true;  
  7. }  
Suppose, we have a condition that you have allowed only Characters, Numbers, and Tab.
  1. function IsCharacterNumber(e) {   
  2.    var charCode = (e.which) ? e.which : e.keyCode;  
  3.    if (!(charCode >= 65 && charCode <= 90) && !(charCode >= 97 && charCode <= 122) && (charCode != 32 && charCode != 8) && !(charCode >= 48 && charCode <= 57) && !(charCode == 9)) {  
  4.    return false;  
  5.    }  
  6. return true;  
  7. }  
Suppose, we have a condition that you allowed only  Character, Numbers, Underscore, and Tab
  1. function IsCharacterNumberUnderScore(e) {  
  2.    var charCode = (e.which) ? e.which : e.keyCode;  
  3.    if (!(charCode >= 65 && charCode <= 90) && !(charCode >= 97 && charCode <= 122) && (charCode != 32 && charCode != 8) && !(charCode >= 48 && charCode <= 57) && !(charCode == 95) && !(charCode == 9)) {  
  4.    return false;  
  5.    }  
  6. return true;  
  7. }  
Sometimes, we need to find how many characters are left to enter. So that time, we can use the below code.
 
"Javascript:Remark();"
 
This line calls the Remark function,
  1. <asp:TextBox ID="txtRemark" Width="200px" runat="server" TextMode="MultiLine" MaxLength="450" 
  2. onkeyup="Javascript:Remark();" Style="max-width: 200px; max-height: 80px; min-width: 200px; min-height: 80px;" onkeypress="return IsCharacterNumber(event,this.value.length <= 450);"></asp:TextBox>  

  3.  <asp:Label ID="Label2" runat="server" CssClass="Label" Text="*" ForeColor="Red"></asp:Label>  
  4.                                 <br />  
  5.   <asp:Label ID="lblRemark" CssClass="LABLE" runat="server" Text="450"></asp:Label>  
  6.    <asp:Label ID="Label2" CssClass="LABLE" runat="server" Text="Character Left"></asp:Label>  

and here, we call the Remark function.
  1. function Remark() {  
  2.             var CharLength = '<%=txtRemark.MaxLength %>';  
  3.             var txtMsg = document.getElementById('ContentPlaceHolder2_txtRemark');  
  4.             var lblCount = document.getElementById('ContentPlaceHolder2_lblRemark');  
  5.             var colorwidth = txtMsg.value.length;  
  6.    
  7.             if (txtMsg.value.length > CharLength) {  
  8.                 txtMsg.value = txtMsg.value.substring(0, CharLength);  
  9.             }  
  10.       document.getElementById('ContentPlaceHolder2_lblRemark').innerHTML = CharLength - txtMsg.value.length;  
  11.         }  
Regular Expression
 
We can use Regular Expression server-side as well as client-side. Here, I will show you how to use the server-side code. The below Namespace is used for Regular Expression.
  1. using System.Text.RegularExpression  
Suppose, we have a condition that you have allowed only alphabet and space.
  1. Regex obj1 = new Regex("[a-zA-Z][a-zA-Z ]+[a-zA-Z]$");   
  2.   
  3. if(!obj1.IsMatch(textbox1.Text))    
  4. {    
  5.    //error Message here    
  6. }    
Suppose, we have a condition where you have allowed entering the app URL.
  1. Regex obj2 = new Regex(@"[\w+]+(/[\w- ;,./?%&=]*)?.aspx\b");      
  2.     
  3. if(!obj2.IsMatch(textbox1.Text))      
  4. {      
  5.    //error Message here      
  6. }    
When we have a condition that you allowed only alphabet, numbers, and underscore.
  1. Regex obj2 = new Regex(@"[\w+]+(/[\w- ;,./?%&=]*)?.aspx\b");    
  2.     
  3. if(!obj2.IsMatch(textbox1.Text))    
  4. {    
  5.    //error Message here    
  6. }    
For a condition where you have allowed only Server IP.
  1. Regex obj4 = new Regex(@"^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$"); Regex obj5 = new Regex(@"([(HTTP|HTTp|HTtp|Http|http|hTTP|htTP:httP)(s)?://]+)([\w- ;,./?%&=]+[:][\d]*(/?))?");    
  2.   
  3. if(!obj4.IsMatch(textbox1.Text))    
  4. {    
  5.    //error Message here    
  6. }    
Suppose, we have allowed only a fully-qualified domain name.
  1. Regex regfqdn = new Regex(@"^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?");    
  2. if(!regfqdn .IsMatch(textbox1.Text))    
  3. {    
  4.    //error Message here    
  5. }  
Suppose we have a condition that you allowed only entering location of file and file path.
  1. Regex obj7 = new Regex(@"[\w-]+(/[\w-]+)+([/]+)?");    
  2.   
  3. if(!obj7.IsMatch(textbox1.Text))    
  4. {    
  5.    //error Message here    
  6. }   
Suppose we have a condition that you allowed only numbers.
  1. Regex obj9 = new Regex("^[0-9]*$");      
  2.     
  3. if(!obj9.IsMatch(textbox1.Text))    
  4. {    
  5.    //error Message here    
  6. }    
Suppose we have condition that you allowed only  alphabet and underscore.
  1. Regex obj1 = new Regex(@"^[a-zA-Z_]*$");   
  2. if(!obj1.IsMatch(textbox1.Text))        
  3. {        
  4.    //error Message here        
  5. }