0

If I have an IP address: 192.100.100.2 and need to ensure that it falls within a range specified using wildcard patterns.

The patterns can be either:

 1. 192. *. *. *
 2. *. *. *. *
 3. 192.1**. *.2

So essentially, an asterisk or three asterisks specify the valid range. Is there something built in in ASP.NET I can use to validate the IP address or would this be more of a custom validation?

Kev
  • 112,868
  • 50
  • 288
  • 373
DotnetDude
  • 11,119
  • 30
  • 94
  • 156

3 Answers3

2

As @AtoMerZ said, just convert your patterns to regular expressions:

    ''//Patterns to search for
    Dim Patterns() As String = {"192.*.*.*", "*.*.*.*", "192.1**.*.2"}

    ''//Test IP
    Dim TestIP = "192.100.100.2"

    ''//Loop through each pattern
    For Each P In Patterns
        ''//Swap two asterisk for two regex digits (\d\d) and one asterisk for one or more digits. Also escape the period
        Trace.WriteLine(System.Text.RegularExpressions.Regex.IsMatch(TestIP, P.Replace("**", "\d\d").Replace("*", "\d+").Replace(".", "\.")))
    Next
Chris Haas
  • 47,821
  • 10
  • 127
  • 248
1

Convert it to string and use Regex.Match

atoMerz
  • 6,868
  • 14
  • 56
  • 99
  • Not mine downvote, but probably because an asterisk (*) means different things in wildcards (match any symbol any number of times) and in regexs (match preceeding char zero or more times) – Alex from Jitbit May 19 '12 at 11:21
-4

Use this validation expression

ValidationExpression="\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"

example code

<asp:TextBox ID="TextBox1" runat="server" Width="321px"></asp:TextBox> 
<asp:Button ID="Button1" runat="server" Text="Validate" />
<br />
<asp:RegularExpressionValidator ValidationExpression="\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
    ID="RegularExpressionValidator1" runat="server" ErrorMessage="Invalid IP !" ControlToValidate="TextBox1"></asp:RegularExpressionValidator></div>
SNaeem
  • 16
  • 2
  • 2
    All that's doing is checking if you have something the looks like an IP address, it's not checking if it lies within a range. – Kev May 11 '11 at 17:14