Macromedia flex 2 Manual
214
Creating Custom Formatters
Extending a Formatter class
You can extend the
Formatter
class to create a custom formatter, or any formatter class. This
section shows an example that extends the
ZipCodeFormatter
class by allowing an extra
format pattern: "#####*####".
In this example, if the user omits a format string, or specifies the default value of
"#####*####", the formatter returns the ZIP code using the format "#####*####". If the
user specifies any other format string, such as a five-digit string in the form "#####", the
custom formatter calls the
"#####*####", the formatter returns the ZIP code using the format "#####*####". If the
user specifies any other format string, such as a five-digit string in the form "#####", the
custom formatter calls the
format()
method in the superclass ZipCodeFormatter class to
format the data.
package myFormatters
{
// formatters/myFormatter/ExtendedZipCodeFormatter.as
import mx.formatters.Formatter
import mx.formatters.ZipCodeFormatter
import mx.formatters.SwitchSymbolFormatter
{
// formatters/myFormatter/ExtendedZipCodeFormatter.as
import mx.formatters.Formatter
import mx.formatters.ZipCodeFormatter
import mx.formatters.SwitchSymbolFormatter
public class ExtendedZipCodeFormatter extends ZipCodeFormatter {
// Constructor
public function ExtendedZipCodeFormatter() {
// Call base class constructor.
super();
// Initialize formatString.
formatString = "#####*####";
}
public function ExtendedZipCodeFormatter() {
// Call base class constructor.
super();
// Initialize formatString.
formatString = "#####*####";
}
// Override format().
override public function format(value:Object):String {
// 1. If the formatString is our new pattern,
// then validate and format it.
override public function format(value:Object):String {
// 1. If the formatString is our new pattern,
// then validate and format it.
if( formatString == "#####*####" ){
if( String( value ).length == 5 )
value = String( value ).concat("0000");
value = String( value ).concat("0000");
if( String( value ).length == 9 ){
var dataFormatter:SwitchSymbolFormatter =
new SwitchSymbolFormatter();
return dataFormatter.formatValue( formatString, value );
}
else {
error="Invalid String Length";
return ""
}
}
var dataFormatter:SwitchSymbolFormatter =
new SwitchSymbolFormatter();
return dataFormatter.formatValue( formatString, value );
}
else {
error="Invalid String Length";
return ""
}
}