Dim str As String str = TextBox1.Text Dim counter As Integer = 1 Dim results As String() results = str.Split(".") Dim IsIPAddress As Boolean IsIPAddress = True Dim scale As Int32 scale = 256 Dim i As Integer For i = 0 To results.GetUpperBound(0) Step 1 If ((CInt(results(i) > scale)) Or (counter > 4)) Then IsIPAddress = False MsgBox("This is not a valid IP address, Please enter the correct one.") TextBox1.Text = Nothing Exit For End If counter += 1 Next
The first step is to drop a RegularExpressionValidator control next to your textbox. Set its ControlToValidate property to the textbox. Set the ErrorMessage to the message you want to give the user when the value is invalid. Finally, set the ValidationExpression to [0-255].[0-255].[0-255].[0-255]. In your code-behind, you can simply check for Page.IsValid to determine if the input was valid or not for all fields that have validators assigned.
Note that the regular expression simply states the groups of values between brackets. You may want to investigate regular expressions further as they provide a very powerful language for expressing requirements on an input string. You may want to take a look at the www.regexplib.com site, which contains a huge number of ready to use expressions for a number of problems.
The code you sent uses the MsgBox function, which is not available/usable on web applications (it's a WinForms message box that is used to display messages on a client application). So if your scenario is actually a WinForms application, here's the code you'd have to use:
' At the class level, a cached version of the compiled expression Shared ipExpression As New Regex("[0-255].[0-255].[0-255].[0-255]", RegexOptions.Compiled) ' In your method that performs validation If Not ipExpression.IsMatch(TextBox1.Text) Then MsgBox("This is not a valid IP address, Please enter the correct one.") TextBox1.Text = Nothing End If
Dig Deeper on ASP.NET development best practices
Related Q&A from Daniel Cazzulino
Here Daniel Cazzulino explains how to load a DSL (domain specific language) domain model instance file programmatically. This requires the .NET type ... Continue Reading
Here we offer a glimpse at 12 of .NET development expert Danny Cazzulino's top ASP.NET questions and answers. Continue Reading
C# developers should NOT be modifying InitializeComponent method in the code-behind (or any of the variable definitions) by hand. Continue Reading
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.