1

I'm trying to come up with the optimal solution for validating IP addresses in Adobe Flex. My current solution is to use a regexp validator and look for dotted quad numbers, see code below. For some reason this will also allow an address like "1.2.3.4.5". Does anyone have a better solution out there?

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
    <fx:Script>
        <![CDATA[
            import mx.controls.Alert;
        ]]>
    </fx:Script>
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
        <mx:RegExpValidator source="{ipAddr}" property="text" 
                            expression="\d+\.\d+\.\d+\.\d+" 
                            invalid="Alert.show('The IP address is invalid');"/>        
    </fx:Declarations>
    <s:TextInput id="ipAddr" x="10" y="10"/>
    <s:Button label="OK" x="10" y="40"/>

</s:Application>
fred basset
  • 9,774
  • 28
  • 88
  • 138
  • Take a look at http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address – Sam DeHaan Mar 27 '12 at 19:59

2 Answers2

2

Regexp to validate an IP is the following:

var regexp:RegExp = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;
trace(regexp.test("10.0.0.5")); // true
trace(regexp.test("243.1.254.15")); // true
trace(regexp.test("256.0.0.0")); // false

Hope that helps

a.s.t.r.o
  • 3,261
  • 5
  • 34
  • 41
0

You could split("\\.") the string, check that the resulting array has a length of either 4 or 6, and that each element is an integer between 0 and 255

Eduardo
  • 8,362
  • 6
  • 38
  • 72