AJAX and IP Addresses

I realize you are disappointed, but the only clever title I could think of for IP Address reminded me of a stupid joke from kindergarten... Never the less.

Here is a cool formula for a client-validated IP address using the AJAX Control Toolkit and asp.net.


<asp:TextBox ID="TextBox1" runat="server" Text='<%# DataValue %>'></asp:TextBox>
<cc1:MaskedEditExtender ID="MaskedEditExtender1" runat="server" TargetControlID="TextBox1"
Mask="NNNNNNNNNNNNNNN" MaskType="None" ClearMaskOnLostFocus="true" Filtered=". " PromptCharacter="" />
<cc1:MaskedEditValidator ID="MaskedEditValidator1" runat="server" ControlToValidate="TextBox1"
InvalidValueMessage="IP Address required (192.168.1.1)" ControlExtender="MaskedEditExtender1" ValidationExpression="^([01]?\d\d?2[0-4]\d25[0-5])\.([01]?\d\d?2[0-4]\d25[0-5])\.([01]?\d\d?2[0-4]\d25[0-5])\.([01]?\d\d?2[0-4]\d25[0-5])$" />


It's really not that involved.


The first control is a normal text box. I happen to be using the new dynamic data stuff from Microsoft. It's pretty cool, but you could bind or not as you want.



The MaskedEditExtender is important because it limits the characters somebody can type to numbers (the N characters in the mask) and the filtered characters (period and space). With 15 spaces maximum, this means the user can't type in too much stuff

Finally, the MaskedEditValidator control has a regular expression that accepts all the valid number mixes from 0-255 for each digit, and only four octets


Once you add it up, you get a client-side filtered IP address with Javascript validation.

Update:

The regular expression could also be written as:
^([01]?\d\d?2[0-4]\d25[0-5])(\.([01]?\d\d?2[0-4]\d25[0-5])){3}$
It works something like this:
  • The carat (^) and dollar sign ($) mean that the expression matches stuff that start and end the input.
  • The first subsection (first set of paranthesis) has three rules: the first "[01]?\d\d?" will match the numbers from 0 to 199 with or without leading zeroes (000 or 0), the second "2[0-4]d" matches numbers from 200 through 249, and the third "25[0-5]" matches values from 250 to 255
  • the next subsection prepends the previous rule with a period (or dot) exactly three more times.

The end result is that you have exactly four numbers from 0-255 separated by three dots.

Comments

Anonymous said…
Great! This was the answer I quoted in this post : http://forums.asp.net/p/1455327/3340910.aspx#3340910

Thanks.

Popular posts from this blog

KnockoutJS, WebAPI, and TypeScript

The most efficient algorithm to scan a bitmap