Adobe Flex 3 Help

Using standard validators

Flex includes the Validator subclasses. You use these validators for common types of data, including credit card numbers, dates, e-mail addresses, numbers, phone numbers, Social Security numbers, strings, and ZIP codes.

Validating credit card numbers

The CreditCardValidator class validates that a credit card number is the correct length, has the correct prefix, and passes the Luhn mod10 algorithm for the specified card type. This validator does not check whether the credit card is an actual active credit card account.

You typically use the cardNumberSource and cardNumberProperty properties to specify the location of the credit card number, and the cardTypeSource and cardTypeProperty properties to specify the location of the credit card type to validate.

The CreditCardValidator class validates that a credit card number is the correct length for the specified card type, as follows:

  • Visa: 13 or 16 digits
  • MasterCard: 16 digits
  • Discover: 16 digits
  • American Express: 15 digits
  • DinersClub: 14 digits, or 16 digits if it also functions as a MasterCard

You specify the type of credit card number to validate by assigning a constant to the cardTypeProperty property. In MXML, valid constant values are:

  • "American Express"
  • "Diners Club"
  • "Discover"
  • "MasterCard"
  • "Visa"

In ActionScript, you can use the following constants to set the cardTypeProperty property:

  • CreditCardValidatorCardType.AMERICAN_EXPRESS
  • CreditCardValidatorCardType.DINERS_CLUB
  • CreditCardValidatorCardType.DISCOVER
  • CreditCardValidatorCardType.MASTER_CARD
  • CreditCardValidatorCardType.VISA

The following example validates a credit card number based on the card type that the users specifies. Any validation errors propagate to the Application object and open an Alert window.

<?xml version="1.0"?>
<!-- validators\CCExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 

    <mx:CreditCardValidator id="ccV" 
        cardTypeSource="{cardTypeCombo.selectedItem}"  
        cardTypeProperty="data"
        cardNumberSource="{cardNumberInput}"  
        cardNumberProperty="text"/>
  
    <mx:Form id="creditCardForm">
        <mx:FormItem label="Card Type">    
            <mx:ComboBox id="cardTypeCombo">
                <mx:dataProvider>
                    <mx:Object label="American Express" 
                        data="American Express"/>
                    <mx:Object label="Diners Club" 
                        data="Diners Club"/>
                    <mx:Object label="Discover" 
                        data="Discover"/>
                    <mx:Object label="MasterCard" 
                        data="MasterCard"/>
                    <mx:Object label="Visa" 
                        data="Visa"/>
                </mx:dataProvider>
            </mx:ComboBox>
        </mx:FormItem>
        <mx:FormItem label="Credit Card Number">
            <mx:TextInput id="cardNumberInput"/>
        </mx:FormItem>
        <mx:FormItem>
            <mx:Button label="Check Credit" click="ccV.validate();"/>
        </mx:FormItem>
    </mx:Form>  
</mx:Application>

The executing SWF file for the previous example is shown below:

The following example performs a similar validation, but uses the source and property properties to specify an object that contains the credit card information. In this example, you use the listener property to configure the validator to display validation error information on the TextInput control:

<?xml version="1.0"?>
<!-- validators\CCExampleSource.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 

    <mx:Script>
        <![CDATA[

            [Bindable]
            public var ccObj:Object = {cardType:String, cardNumber:String};
            
            public function valCC():void
            {            
                // Populate ccObj with the data from the form.
                ccObj.cardType = cardTypeCombo.selectedItem.data;
                ccObj.cardNumber = cardNumberInput.text;
                // Validate ccObj.
                ccV.validate();                
            }    
        ]]>    
    </mx:Script>

    <mx:CreditCardValidator id="ccV" 
        source="{this}"  
        property="ccObj"
        listener="{cardNumberInput}"/>
  
    <mx:Form id="creditCardForm">
        <mx:FormItem label="Card Type">    
            <mx:ComboBox id="cardTypeCombo">
                <mx:dataProvider>
                    <mx:Object label="American Express" 
                        data="American Express"/>
                    <mx:Object label="Diners Club" 
                        data="Diners Club"/>
                    <mx:Object label="Discover" 
                        data="Discover"/>
                    <mx:Object label="MasterCard" 
                        data="MasterCard"/>
                    <mx:Object label="Visa" 
                        data="Visa"/>
                </mx:dataProvider>
            </mx:ComboBox>
        </mx:FormItem>
        <mx:FormItem label="Credit Card Number">
            <mx:TextInput id="cardNumberInput"/>
        </mx:FormItem>
        <mx:FormItem>
            <mx:Button label="Check Credit" click="valCC();"/>
        </mx:FormItem>
    </mx:Form>  
</mx:Application>

The executing SWF file for the previous example is shown below:

Validating currency

The CurrencyValidator class checks that a string is a valid currency expression based on a set of parameters. The CurrencyValidator class defines the properties that let you specify the format of the currency value, whether to allow negative values, and the precision of the values.

The following example uses the CurrencyValidator class to validate a currency value entered in U.S. dollars and in Euros:

<?xml version="1.0"?>
<!-- validators\CurrencyExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 

    <!-- Example for US currency. -->
    <mx:CurrencyValidator id="usV" 
        source="{priceUS}" property="text"
        alignSymbol="left"
        trigger="{valButton}"
        triggerEvent="click"/>

    <mx:Label text="Enter a US-formatted price:"/>
    <mx:TextInput id="priceUS"/>

    <!-- Example for European currency. -->
    <mx:CurrencyValidator id="eurV" 
        source="{priceEU}" property="text"
        alignSymbol="right" 
        decimalSeparator="," thousandsSeparator="."
        trigger="{valButton}"
        triggerEvent="click"/>

    <mx:Label text="Enter a European-formatted price:"/>
    <mx:TextInput id="priceEU"/>
    
    <mx:Button id="valButton" label="Validate Currencies"/>
</mx:Application>

The executing SWF file for the previous example is shown below:

Validating dates

The DateValidator class validates that a String, Date, or Object contains a proper date and matches a specified format. Users can enter a single digit or two digits for month, day, and year. By default, the validator ensures that the following information is provided:

  • The month is between 1 and 12 (or 0-11 for Date objects)
  • The day is between 1 and 31
  • The year is a number

If you specify a single String to validate, the String can contain digits and the formatting characters that the allowedFormatChars property specifies, including the slash (/), backslash (\), dash (-), and period (.) characters. By default, the input format of the date in a String is "mm/dd/yyyy" where "mm" is the month, "dd" is the day, and "yyyy" is the year. You can use the inputFormat property to specify a different format.

You can also specify to validate a date represented by a single Object, or by multiple fields of different objects. For example, you could use a data model that contains three fields that represent the day, month, and year portions of a date, or three TextInput controls that let a user enter a date as three separate fields. Even if you specify a date format that excludes a day, month, or year element, you must specify all three fields to the validator.

The following table describes how to specify the date to the DateValidator:

Validation source

Required properties

Default listener

String object containing the date

Use the source and property properties to specify the String.

Flex associates error messages with the field specified by the property property.

Date object containing the date

Use the source and property properties to specify the Date.

Flex associates error messages with the field specified by the property property.

Object or multiple fields containing the day, month, and year

Use all of the following properties to specify the day, month, and year inputs: daySource, dayProperty, monthSource, monthProperty, yearSource, and yearProperty.

Flex associates error messages with the field specified by the daySource, monthSource, and yearSource properties, depending on the field that caused the validation error.

The following example validates a date entered into a form:

<?xml version="1.0"?>
<!-- validators\DateExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 

    <mx:DateValidator id="dateV" 
        daySource="{dayInput}" dayProperty="text" 
        monthSource="{monthInput}" monthProperty="text" 
        yearSource="{yearInput}" yearProperty="text"/>

    <mx:Form >
        <mx:FormItem label="Month">
            <mx:TextInput id="monthInput"/>
        </mx:FormItem>
        <mx:FormItem label="Day">
            <mx:TextInput id="dayInput"/>
        </mx:FormItem>
        <mx:FormItem label="Year">
            <mx:TextInput id="yearInput"/>
        </mx:FormItem>
        <mx:FormItem>
            <mx:Button label="Check Date" click="dateV.validate();"/>   
        </mx:FormItem>
    </mx:Form>

    <!-- Alternate method for a single field containing the date. -->
    <mx:Model id="alternateDate">
        <dateInfo>
            <date>{dateInput.text}</date>
        </dateInfo>
    </mx:Model>

    <mx:DateValidator id="stringDateV" 
        source="{dateInput}" property="text" 
        inputFormat="dd/mm/yyyy"
        allowedFormatChars="*#~/"/>

    <mx:Form>
        <mx:FormItem label="Date of Birth (dd/mm/yyyy)">
            <mx:TextInput id="dateInput"/>
        </mx:FormItem>
        <mx:FormItem>
            <mx:Button label="Check Date" click="stringDateV.validate();"/>   
        </mx:FormItem>
    </mx:Form>
</mx:Application>

The executing SWF file for the previous example is shown below:

In the next example, you validate a Date object:

<?xml version="1.0"?>
<!-- validators\DateObjectExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 

    <mx:Script>
        <![CDATA[        
            import mx.controls.Alert;

            // myDate is set to the current date and time.
            [Bindable]
            public var myDate:Date = new Date();                       
        ]]>
    </mx:Script>

    <mx:DateValidator id="dateV" 
        source="{this}" property="myDate"
        valid="Alert.show('Validation Succeeded!');"/>

    <mx:Button label="Check Date" click="dateV.validate();"/>   
</mx:Application>

The executing SWF file for the previous example is shown below:

Validating e-mail addresses

The EmailValidator class validates that a string has an at sign character (@) and a period character (.) in the domain. You can use IP domain names if they are enclosed in square brackets; for example, myname@[206.132.22.1]. You can use individual IP numbers from 0 to 255. This validator does not check whether the domain and user name actually exist.

The following example validates an e-mail address to ensure that it is formatted correctly:

<?xml version="1.0"?>
<!-- validators\EmailExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 

    <mx:Form id="contactForm">
        <mx:FormItem id="homePhoneItem" label="Home Phone">
            <mx:TextInput id="homePhoneInput"/>
        </mx:FormItem>
        <mx:FormItem id="cellPhoneItem" label="Cell Phone">
            <mx:TextInput id="cellPhoneInput"/>
        </mx:FormItem>
        <mx:FormItem id="emailItem" label="Email">
            <mx:TextInput id="emailInput"/> 
        </mx:FormItem>
    </mx:Form>

    <mx:PhoneNumberValidator id="pnVHome" 
        source="{homePhoneInput}" property="text"/>
    <mx:PhoneNumberValidator id="pnVCell" 
        source="{cellPhoneInput}" property="text"/>
    <mx:EmailValidator id="emV" 
        source="{emailInput}" property="text"/>
</mx:Application>

The executing SWF file for the previous example is shown below:

Validating numbers

The NumberValidator class ensures that a string represents a valid number. This validator can ensure that the input falls within a given range (specified by the minValue and maxValue properties), is an integer (specified by the domain property), is non-negative (specified by the allowNegative property), and does not exceed the specified precision. The NumberValidator correctly validates formatted numbers (for example, "12,345.67"), and you can customize its thousandsSeparator and decimalSeparator properties for internationalization.

The following example uses the NumberValidator class to ensure that an integer is between 1 and 10:

<?xml version="1.0"?>
<!-- validators\NumberExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 

    <mx:Form >
        <mx:FormItem 
            label="Number of Widgets (max 10 per customer)">
            <mx:TextInput id="quantityInput"/>
        </mx:FormItem>   
        <mx:FormItem >  
            <mx:Button label="Submit"/>
        </mx:FormItem>   
    </mx:Form>

    <mx:NumberValidator id="numV" 
        source="{quantityInput}" property="text" 
        minValue="1" maxValue="10" domain="int"/>
</mx:Application>

The executing SWF file for the previous example is shown below:

Validating phone numbers

The PhoneNumberValidator class validates that a string is a valid phone number. A valid phone number contains at least 10 digits, plus additional formatting characters. This validator does not check if the phone number is an actual active phone number.

The following example uses two PhoneNumberValidator tags to ensure that the home and mobile phone numbers are entered correctly:

<?xml version="1.0"?>
<!-- validators\PhoneExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 

    <mx:Form id="contactForm">
        <mx:FormItem id="homePhoneItem" label="Home Phone">
            <mx:TextInput id="homePhoneInput"/>
        </mx:FormItem>
        <mx:FormItem id="cellPhoneItem" label="Cell Phone">
            <mx:TextInput id="cellPhoneInput"/>
        </mx:FormItem>
        <mx:FormItem id="emailItem" label="Email">
            <mx:TextInput id="emailInput"/> 
        </mx:FormItem>
    </mx:Form>

    <mx:PhoneNumberValidator id="pnVHome" 
        source="{homePhoneInput}" property="text"/>
    <mx:PhoneNumberValidator id="pnVCell" 
        source="{cellPhoneInput}" property="text"/>
    <mx:EmailValidator id="emV" 
        source="{emailInput}" property="text"/>
</mx:Application>

The executing SWF file for the previous example is shown below:

Validating using regular expressions

The RegExpValidator class lets you use a regular expression to validate a field. You pass a regular expression to the validator by using the expression property, and additional flags to control the regular expression pattern matching by using the flags property.

The validation is successful if the validator can find a match of the regular expression in the field to validate. A validation error occurs when the validator finds no match.

You use regular expressions with the RegExpValidator. For information on writing regular expressions, see Programming ActionScript 3.0.

The RegExpValidator class dispatches the valid and invalid events. For an invalid event, the event object is an instance of the ValidationResultEvent class, and it contains an Array of ValidationResult objects.

However, for a valid event, the ValidationResultEvent object contains an Array of RegExpValidationResult objects. The RegExpValidationResult class is a child class of the ValidationResult class, and contains additional properties that you use with regular expressions, including the following:

matchedIndex 

An integer that contains the starting index in the input String of the match.



matchedString 

A String that contains the substring of the input String that matches the regular expression.



matchedSubStrings 

An Array of Strings that contains parenthesized substring matches, if any. If no substring matches are found, this Array is of length 0. Use matchedSubStrings[0] to access the first substring match.



The following example uses the regular expression ABC\d to cause the validator to match a pattern consisting of the letters A, B, and C in sequence followed by any digit:

<?xml version="1.0"?>
<!-- validators\RegExpExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 

    <mx:Script>
        <![CDATA[
          import mx.events.ValidationResultEvent;
          import mx.validators.*;
    
          private function handleResult(event:ValidationResultEvent):void {
              if (event.type == "valid")
              {
                  // For valid events, the results Array contains
                  // RegExpValidationResult objects.
                  var xResult:RegExpValidationResult;
                  myTA.text="";
                  for (var i:uint = 0; i < event.results.length; i++)
                  {
                      xResult = event.results[i];
                      myTA.text=myTA.text + xResult.matchedIndex + " " +
                          xResult.matchedString + "\n";
                  }
              }
              else
              {
                  // Not necessary, but if you needed to access it, 
                  // the results array contains ValidationResult objects. 
                  var result:ValidationResult;
                  myTA.text="";           
              }       
          }
        ]]>
    </mx:Script>

    <mx:RegExpValidator id="regExpV" 
        source="{exp}" property="text" 
        flags="g" 
        expression="{source.text}" 
        valid="handleResult(event);" 
        invalid="handleResult(event);"/>
    
    <mx:Form>
        <mx:FormItem label="Search string">
            <mx:TextInput id="exp"/>
        </mx:FormItem>
        <mx:FormItem label="Regular expression">
            <mx:TextInput id="source" text="ABC\d"/>
        </mx:FormItem>
        <mx:FormItem label="Results">
            <mx:TextArea id="myTA"/>
        </mx:FormItem>
    </mx:Form>
</mx:Application>

The executing SWF file for the previous example is shown below:

In this example, you specify the regular expression in the TextInput control named source, and bind it to the expression property of the validator. You can modify the regular expression by entering a new expression in the TextInput control. A value of g for the flags property specifies to find multiple matches in the input field.

The event handler for the valid event writes to the TextArea control the index in the input String and matching substring of all matches of the regular expression. The invalid event handler clears the TextArea control.

Validating social security numbers

The SocialSecurityValidator class validates that a string is a valid United States Social Security Number. This validator does not check if the number is an existing Social Security Number.

The following example validates a Social Security Number:

<?xml version="1.0"?>
<!-- validators\SSExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 

    <mx:Form id="identityForm">
        <mx:FormItem id="ssnItem" label="Social Security Number">
            <mx:TextInput id="ssnField"/>
        </mx:FormItem>
        <mx:FormItem id="licenseItem" label="Driver's License Number">
            <mx:TextInput id="licenseInput"/> <!-- Not validated -->
        </mx:FormItem>
    </mx:Form>

    <mx:SocialSecurityValidator id="ssV" 
        source="{ssnField}" property="text"/>
</mx:Application>

The executing SWF file for the previous example is shown below:

Validating strings

The StringValidator class validates that a string length is within a specified range. The following example ensures that a string is between 6 and 12 characters long:

<?xml version="1.0"?>
<!-- validators\StringExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 

    <mx:Form id="membershipForm">
        <mx:FormItem id="fullNameItem" label="Full Name">
        <!-- Not validated -->
            <mx:TextInput id="fullNameInput"/> 
        </mx:FormItem>
        <mx:FormItem id="userNameItem" label="Username">
            <mx:TextInput id="userNameInput"/>
        </mx:FormItem>
    </mx:Form>

    <mx:StringValidator source="{userNameInput}" property="text" 
        minLength="6" maxLength="12"/>
</mx:Application>

The executing SWF file for the previous example is shown below:

Validating ZIP codes

The ZipCodeValidator class validates that a string has the correct length for a five-digit ZIP code, a five-digit+four-digit United States ZIP code, or a Canadian postal code.

The following example validates either a United States ZIP code or a Canadian postal code:

<?xml version="1.0"?>
<!-- validators\ZCExample.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> 

    <mx:Form id="addressForm">
        <mx:FormItem id="zipCodeItem" label="Zip Code">
            <mx:TextInput id="zipInput"/>
        </mx:FormItem>
        <mx:FormItem id="submitArea">  
            <mx:Button label="Submit"/>
        </mx:FormItem>   
    </mx:Form>

    <mx:ZipCodeValidator id="zipV" 
        source="{zipInput}" property="text" 
        domain="US or Canada"/>
</mx:Application>

The executing SWF file for the previous example is shown below: