fred basset
fred basset

Reputation: 10092

Best way to validate an IP address in Adobe Flex

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>

Upvotes: 1

Views: 1868

Answers (2)

a.s.t.r.o
a.s.t.r.o

Reputation: 3338

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

Upvotes: 2

Eduardo
Eduardo

Reputation: 8402

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

Upvotes: 0

Related Questions