All formatters are subclasses of the mx.formatters.Formatter class.
The Formatter class declares a format() method
that takes a value and returns a String value.
Writing an error handler function for an MX formatter
For most formatters, when an error occurs, the format() method
returns an empty string is and a string describing the error is
written to the formatter’s error property. You
can check for an empty string in the return value of the format() method,
and if found, access the error property to determine
the cause of the error.
Alternatively, you can write an error handler function that returns
an error message for a formatting error. The following example shows
a simple error handler function:
<?xml version="1.0"?>
<!-- formatters\FormatterSimpleErrorForDevApps.mxml -->
<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">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
private function formatWithError(value:Object):String {
var formatted:String = myFormatter.format(value);
if (formatted == "") {
if (myFormatter.error != null ) {
if (myFormatter.error == "Invalid value") {
formatted = ": The value is not valid.";
}
else {
formatted = ": The formatString is not valid.";
}
}
}
return formatted;
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Declare a formatter and specify formatting properties.-->
<mx:DateFormatter id="myFormatter"
formatString="MXXXMXMXMXMXM"/>
</fx:Declarations>
<!-- Trigger the formatter while populating a string with data.-->
<s:TextInput id="myTI"
width="75%"
text="Your order shipped on {formatWithError('May 23, 2005')}"/>
</s:Application>
The executing SWF file for the previous example is shown below:
In this example, you define a DateFormatter with
an invalid format string. You then use the formatWithError() method
to invoke the formatter in the TextInput control, rather than calling
the Date formatter’s format() method directly.
In this example, if either the input string or the format string
is invalid, the formatWithError() method returns
an error message instead of a formatted String value.
Formatting currency with an MX formatter
The
MX CurrencyFormatter class
provides the same features as the NumberFormatter class, plus a
currency symbol. It has two additional properties: currencySymbol and alignSymbol.
(For more information about the NumberFormatter class, see Formatting numbers with an MX formatter.)
The CurrencyFormatter class provides basic formatting options
for numeric data, including decimal formatting, thousands separator
formatting, and negative sign formatting. The format() method
accepts a Number value or a number formatted as a String value and
formats the resulting string.
When a number formatted as a String is passed to the format() method,
the function parses the string from left to right and attempts to
extract the first sequence of numbers it encounters. The function
parses the thousands separators and decimal separators along with
their trailing numbers. The parser searches for a comma (,) for
the thousands separator unless you set a different character in
the thousandsSeparatorFrom property. The parser
searches for a period (.) for the decimal separator unless you define
a different character in the decimalSeparator property.
Note: When a number is provided to the format() method
as a String value, a negative sign is recognized if it is a dash
(-) immediately preceding the first number in the sequence. A dash,
space, and then a first number are not interpreted as a negative sign.
Example: Using the MX CurrencyFormatter class
The following example
uses the CurrencyFormatter class in an MXML file:
<?xml version="1.0"?>
<!-- formatters\MainCurrencyFormatter.mxml -->
<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">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
// Define variable to hold the price.
[Bindable]
private var todaysPrice:Number=4025;
]]>
</fx:Script>
<fx:Declarations>
<!-- Declare a CurrencyFormatter and define parameters.-->
<mx:CurrencyFormatter id="Price" precision="2"
rounding="none"
decimalSeparatorTo="."
thousandsSeparatorTo=","
useThousandsSeparator="true"
useNegativeSign="true"
currencySymbol="$"
alignSymbol="left"/>
</fx:Declarations>
<!-- Trigger the formatter while populating a string with data.-->
<s:TextInput text="Today's price is {Price.format(todaysPrice)}."
width="200"/>
</s:Application>
The executing SWF file for the previous example is shown below:
At run time, the following
text is displayed:
Today’s price is $4,025.00.
Error handling: MX CurrencyFormatter class
If an error occurs,
Flex returns an empty string and saves a description of the error in
the error property.
An error points to a problem with the value being submitted or the
format string containing the user settings, as described in the following
table:
Value of error property
When error occurs
Invalid value
An invalid numeric value is passed to the format() method.
The value should be a valid number in the form of a Number or a
String.
Invalid format
One or more of the parameters contain an
unusable setting.
Formatting dates with an MX formatter
The MX DateFormatter class
gives you a wide range of combinations for displaying date and time
information. The format() method accepts a Date object,
which it converts to a String based on a user-defined pattern. The format() method
can also accept a String-formatted date, which it attempts to parse
into a valid Date object prior to formatting.
The DateFormatter class has a parseDateString() method
that accepts a date formatted as a String. The parseDateString() method
examines sections of numbers and letters in the String to build
a Date object. The parser is capable of interpreting long or abbreviated
(three-character) month names, time, am and pm, and various representations
of the date.
The hour value in the String must be between 0 and 23, inclusive.
The minutes and seconds value must be between 0 and 59, inclusive.
If the parseDateString() method is unable to parse
the String into a Date object, it returns null.
The following examples show some of the ways strings can be parsed:
"12/31/98" or "12-31-98" or "1998-12-31" or "12/31/1998"
"Friday, December 26, 2005 8:35 am"
"Jan. 23, 1989 11:32:25"
The DateFormatter class parses strings from left to right. A
date value should appear before the time and must be included. The
time value is optional. A time signature of 0:0:0 is the Date object’s
default for dates that are defined without a time. Time zone offsets
are not parsed.
Using Pattern strings
You provide the DateFormatter class
with a string of pattern letters, which it parses to determine the
appropriate formatting. You must understand how to compose the string
of pattern letters to control the formatting options and the format
of the string that is returned.
You compose a pattern string
by using specific uppercase letters: for example, YYYY/MM. The DateFormatter
pattern string can contain other text in addition to pattern letters.
To form a valid pattern string, you need only one pattern letter.
When
you create a pattern string, you usually repeat pattern letters.
The number of repeated letters determines the presentation. For
numeric values, the number of pattern letters is the minimum number
of digits; shorter numbers are zero-padded to this amount. For example,
the four-letter pattern string “YYYY” corresponds to a four-digit
year value.
In cases where there is a corresponding mapping
of a text description—for instance, the name of a month—the full
form is used if the number of pattern letters is four or more; otherwise,
a short or abbreviated form is used, if available. For example,
if you specify the pattern string “MMMM” for month, the formatter requires
the full month name, such as “December”, instead of the abbreviated month
name, such as “Dec”.
For time values, a single pattern letter
is interpreted as one or two digits. Two pattern letters are interpreted
as two digits.
The following table describes each of the available
pattern letters:
Pattern letter
Description
Y
Year. If the number of pattern letters is
two, the year is truncated to two digits; otherwise, it appears
as four digits. The year can be zero-padded, as the third example
shows in the following set of examples:
Examples:
YY
= 05
YYYY = 2005
YYYYY = 02005
M
Month in year. The format depends on the
following criteria:
If the number of pattern letters
is one, the format is interpreted as numeric in one or two digits.
If the number of pattern letters is two, the format is interpreted
as numeric in two digits.
If the number of pattern letters is three, the format is
interpreted as short text.
If the number of pattern letters is four, the format is interpreted
as full text.
Examples:
M = 7
MM=
07
MMM=Jul
MMMM= July
D
Day in month. While a single-letter pattern
string for day is valid, you typically use a two-letter pattern
string.
Examples:
D=4
DD=04
DD=10
E
Day in week. The format depends on the following
criteria:
If the number of pattern letters is one,
the format is interpreted as numeric in one or two digits.
If the number of pattern letters is two, the format is interpreted
as numeric in two digits.
If the number of pattern letters is three, the format is
interpreted as short text.
If the number of pattern letters is four, the format is interpreted
as full text.
Examples:
E = 1
EE
= 01
EEE = Mon
EEEE = Monday
A
am/pm indicator.
J
Hour in day (0-23).
H
Hour in day (1-24).
K
Hour in am/pm (0-11).
L
Hour in am/pm (1-12).
N
Minute in hour.
Examples:
N
= 3
NN = 03
S
Second in minute.
Examples:
SS
= 30
Q
Millisecond in seconds.Example:s: QQ = 78QQQ
= 078
Other text
You can add other text into the pattern
string to further format the string. You can use punctuation, numbers,
and all lowercase letters. You should avoid uppercase letters because
they may be interpreted as pattern letters.
Example:
EEEE,
MMM. D, YYYY at L:NN A = Tuesday, Sept. 8, 2005 at 1:26 PM
The following table shows sample pattern
strings and the resulting presentation:
Pattern
Result
YYYY.MM.DD at HH:NN:SS
2005.07.04 at 12:08:56
EEEE, MMM. D, YYYY at L:NN:QQQ A
Tuesday, Sept. 8, 2005 at 1:26:012 PM
EEE, MMM D, 'YY
Wed, Jul 4, '05
H:NN A
12:08 PM
HH o'clock A
12 o'clock PM
K:NN A
0:08 PM
YYYYY.MMMM.DD. JJ:NN A
02005.July.04. 12:08 PM
EEE, D MMM YYYY HH:NN:SS
Wed, 4 Jul 2005 12:08:56
Example: Using the DateFormatter class
The following example uses
the DateFormatter class
in an MXML file for formatting a Date object as a String:
<?xml version="1.0"?>
<!-- formatters\MainDateFormatter.mxml -->
<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">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
// Define variable to hold the date.
[Bindable]
private var today:Date = new Date();
]]>
</fx:Script>
<fx:Declarations>
<!-- Declare a DateFormatter and define parameters.-->
<mx:DateFormatter id="DateDisplay"
formatString="MMMM D, YYYY"/>
</fx:Declarations>
<!-- Display the date in a TextArea control.-->
<s:TextInput id="myTA" text="{DateDisplay.format(today)}"/>
</s:Application>
The executing SWF file for the previous example is shown below:
At run time, the TextInput
control displays the current date.
Error handling: DateFormatter class
If an error occurs, Flex
returns an empty string and saves a description of the error in
the error property.
An error points to a problem with the value being submitted or the
format string containing the user settings, as described in the following
table:
Value of error property
When error occurs
Invalid value
A value that is not a Date object is passed
to the format() method. (An empty argument is allowed.)
Invalid format
The formatString property
is set to empty ("").
There is less than one pattern letter in the formatString property.
Formatting numbers with an MX formatter
The MX NumberFormatter class
provides basic formatting options for numeric data, including decimal
formatting, thousands separator formatting, and negative sign formatting.
The format() method accepts a number or a number
formatted as a String value, and formats the resulting string.
When a number formatted as a String value is passed to the format() method, the
function parses the string from left to right and attempts to extract
the first sequence of numbers it encounters. The function parses
the thousands separators and decimal separators along with their
trailing numbers. The parser searches for a comma (,) for the thousands
separator unless you set a different character in the thousandsSeparatorFrom property.
The parser searches for a period (.) for the decimal separator unless
you define a different character in the decimalSeparator property.
Note: The format() method recognizes
a dash (-) immediately preceding the first number in the sequence
as a negative number. A dash, space, and then number sequence are
not interpreted as a negative number.
The rounding and precision properties
of the MX NumberFormatter class affect the formatting of the decimal
in a number. If you use both rounding and precision properties,
rounding is applied first, and then the decimal length is set by
using the specified precision value. This lets you round a number
and still have a trailing decimal; for example, 303.99 = 304.00.
Example: Using the MX NumberFormatter class
The following example
uses the MX NumberFormatter class
in an MXML file:
<?xml version="1.0"?>
<!-- formatters\MainNumberFormatter.mxml -->
<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">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
// Define variable to hold the number.
[Bindable]
private var bigNumber:Number = 6000000000.65;
]]>
</fx:Script>
<fx:Declarations>
<!-- Declare and define parameters for the NumberFormatter.-->
<mx:NumberFormatter id="PrepForDisplay"
precision="0"
rounding="up"
decimalSeparatorTo="."
thousandsSeparatorTo=","
useThousandsSeparator="true"
useNegativeSign="true"/>
</fx:Declarations>
<!-- Trigger the formatter while populating a string with data.-->
<s:TextInput text="{PrepForDisplay.format(bigNumber)}"/>
</s:Application>
The executing SWF file for the previous example is shown below:
At run time, the following
text appears:
6,000,000,001
Error handling: MX NumberFormatter class
If an error occurs,
Flex returns an empty string and saves a description of the error in
the error property.
An error refers to a problem with the value being submitted or the
format string that contains the user settings, as described in the
following table:
Value of error property
When error occurs
Invalid value
An invalid numeric value is passed to the format() method.
The value should be a valid number in the form of a Number or a
String.
Invalid format
One or more of the parameters contain an
unusable setting.
Formatting phone numbers with an MX formatter
The PhoneFormatter class
lets you format a phone number by adjusting the format of the area
code and the subscriber code. You can also adjust the country code
and configuration for international formats. The value passed into
the PhoneFormatter.format() method must be a Number
object or a String object with only digits.
The PhoneFormatter formatString property accepts
a formatted string as a definition of the format pattern. The following
table shows common options for formatString values.
The format() method for the PhoneFormatter accepts
a sequence of numbers. The numbers correspond to the number of placeholder
(#) symbols in the formatString value. The number
of placeholder symbols in the formatString property
and the number of digits in the format() method
value must match.
formatString value
Input
Output
###-####
1234567
(xxx) 456-7890
(###) ### ####
1234567890
(123) 456-7890
###-###-####
11234567890
123-456-7890
#(###) ### ####
11234567890
1(123) 456 7890
#-###-###-####
11234567890
1-123-456-7890
+###-###-###-####
1231234567890
+123-123-456-7890
In the preceding table, dashes (-) are used as separator elements
where applicable. You can substitute period (.) characters or blank
spaces for the dashes. You can change the default allowable character
set as needed by using the validPatternChars property.
You can change the default character that represents a numeric placeholder
by using the numberSymbol property (for example,
to change from # to $).
Note: A shortcut is provided for the United States
seven-digit format. If the areaCode property contains
a value and you use the seven-digit format string, a seven-digit
format entry automatically adds the area code to the string returned.
The default format for the area code is (###).
You can change this by using the areaCodeFormat property.
You can format the area code any way you want as long as it contains
three number placeholders.
Example: Using the PhoneFormatter class
The following example uses
the PhoneFormatter class
in an MXML file:
<?xml version="1.0"?>
<!-- formatters\MainPhoneFormatter.mxml -->
<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">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
// Define variable to hold the phone number.
[Bindable]
private var newNumber:Number = 1234567;
]]>
</fx:Script>
<fx:Declarations>
<!-- Declare a PhoneFormatter and define formatting parameters.-->
<mx:PhoneFormatter id="PhoneDisplay"
areaCode="415"
formatString="###-####"/>
</fx:Declarations>
<!-- Trigger the formatter while populating a string with data-->
<s:TextInput id="myTI"
initialize="myTI.text=PhoneDisplay.format(newNumber);"/>
</s:Application>
The executing SWF file for the previous example is shown below:
At run time, the following
text is displayed:
(415) 123-4567
Error handling: PhoneFormatter class
If an error occurs, Flex
returns an empty string and saves a description of the error in
the error property.
An error points to a problem with the value being submitted or the
format string containing the user settings, as described in the following
table:
Value of error property
When error occurs
Invalid value
An invalid numeric value is passed
to the format() method. The value should be a valid number
in the form of a Number or a String.
The value contains a different number of digits than what
is specified in the format string.
Invalid format
One or more of the characters
in the formatString do not match the allowed characters specified
in the validPatternChars property.
The areaCodeFormat property is specified
but does not contain exactly three numeric placeholders.
Formatting zip codes with an MX formatter
The ZipCodeFormatter class
lets you format five-digit or nine-digit United States ZIP codes
and six-character Canadian postal codes. The ZipCodeFormatter class’s formatString property
accepts a formatted string as a definition of the format pattern.
The formatString property is optional. If it is
omitted, the default value of ##### is used.
The number of digits in the value to be formatted and the value
of the formatString property must be five or nine
for United States ZIP codes, and six for Canadian postal codes.
The following table shows common formatString values,
input values, and output values:
formatString value
Input
Output
Format
#####
94117, 941171234
94117, 94117
Five-digit U.S. ZIP code
#####-####
941171234, 94117
94117-1234, 94117-0000
Nine-digit U.S. ZIP code
### ###
A1B2C3
A1B 2C3
Six-character Canadian postal code
For United States ZIP codes, if a nine-digit format is requested
and a five-digit value is supplied, ‑0000 is appended
to the value to make it compliant with the nine-digit format. Inversely,
if a nine-digit value is supplied for a five-digit format, the number
is truncated to five digits.
For Canadian postal codes, only a six-digit value is allowed
for either the formatString or the input value.
Note: For United States ZIP codes, only numeric characters
are valid. For Canadian postal codes, alphanumeric characters are
allowed. Alphabetic characters must be in uppercase.
Example: Using the ZipCodeFormatter class
The following example
uses the ZipCodeFormatter class
in an MXML file:
<?xml version="1.0"?>
<!-- formatters\MainZipFormatter.mxml -->
<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">
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
// Define variable to hold the ZIP code.
[Bindable]
private var storedZipCode:Number=123456789;
]]>
</fx:Script>
<fx:Declarations>
<!-- Declare a ZipCodeFormatter and define parameters.-->
<mx:ZipCodeFormatter id="ZipCodeDisplay"
formatString="#####-####"/>
</fx:Declarations>
<!-- Trigger the formatter while populating a string with data.-->
<s:TextInput text="{ZipCodeDisplay.format(storedZipCode)}"/>
</s:Application>
The executing SWF file for the previous example is shown below:
At run time, the following
text is displayed:
12345-6789
Error handling: ZipCodeFormatter class
If an error occurs, Flex
returns an empty string and saves a description of the error in
the error property.
An error refers to a problem with the value being submitted or the
format string containing the user settings, as described in the
following table:
Value of error property
When error occurs
Invalid value
An invalid numeric value is passed
to the format() method. The value should be a valid number
in the form of a Number or a String, except for Canadian postal
codes, which allow alphanumeric values.
The number of digits does not match the allowed digits from
the formatString property.
Invalid format
One or more of the characters
in the formatString do not match the allowed characters specified
in the validFormatChars property.
The number of numeric placeholders does not equal 9, 5, or
6.