ASP.NET Validation Tips and Tricks (Part1)

Submitted by planetsourcecode on
Tips1# Validate an IP address We can easily validate an IP address by Adding Namespace using System.Text.RegularExpressions; public class IPAddressTextBox: RegExTextBox { public IPAddressTextBox() { InitializeComponent(); this.ValidationExpression = @"^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$"; this.ErrorMessage = "The IP address must be in the form of 111.111.111.111"; } Tips2# Validate SSN(Social Security Number) using System.Text.RegularExpressions; public class SsnTextBox: RegExTextBox { public SsnTextBox() { InitializeComponent(); this.ValidationExpression = @"^\d{3}-\d{2}-\d{4}$"; this.ErrorMessage = "The social security number must be in the form of 555-55-5555"; } } Tips3# How to restrict length size in text box. The following function is used to restrict length size in text box function MaxNumber(id,size) { if(id!=null) { var no =id.length; if(no>=size) { alert("Maximum length exceeds"); event.returnValue=false; return false; } else { return true; } }//End of IF }//End Of Funciton Tips4# How to validate an IP address from 1.0.0.0 to 255.255.2The following code sample will help in validating an IP address Public Function ValidIP(ByVal addr As String) As Boolean 'create our match pattern Dim pat As String = "^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\." & _ "([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$" Dim check As New Text.RegularExpressions.Regex(pat) 'boolean variable to hold the status Dim valid As Boolean = False If addr = "" Then valid = False Else valid = check.IsMatch(addr, 0) End If 'return the results Return valid End Function 55.255 Tips5# How to check and see if a string is all uppercase in c# The following code sample helps to check and see if a string is all uppercase in c#. Pass the method a string, read the results (true/false). Need reference to System.Text.RegularExpressions Namespace using System.Text.RegularExpressions; public bool IsUppercase(string str) //string to check { bool upper; //to hold return value string pattern = "[a-z]"; //variable to hold the search pattern try { Regex AllCaps = new Regex(pattern); if (AllCaps.IsMatch(str)) { upper = false; } upper = true; } catch { upper = false; } return upper; } About the author: Planet Source Code is a place for all developer providing free source codes, articles, complete projects,complete application in PHP, C/C++, Javascript, Visual Basic, Cobol, Pascal, ASP/VBScript, AJAX, SQL, Perl, Python, Ruby, Mobile Development