Checking whether a color name is a valid color in Flex using the StyleManager class

by Peter deHaan on September 13, 2007

in StringUtil, StyleManager

The following example shows how to use the static StyleManager.isColorName() method to check whether a color name is valid or not. This method takes a single parameter, colorName, and returns a Boolean value representing whether the parameter is a valid alias for a color.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/09/13/checking-whether-a-color-name-is-a-valid-color-in-flex-using-the-stylemanager-class/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.styles.StyleManager;
            import mx.utils.StringUtil;

            private function button_click(evt:MouseEvent):void {
                /* Remove leading and trailing whitespace. */
                var str:String = StringUtil.trim(textInput.text);
                var isColor:Boolean = StyleManager.isColorName(str);

                /* If it is a valid color, set the background color
                   and remove the error string, if any. Else, set the
                   background color to the constant NOT_A_COLOR from
                   the StyleManager class and set the error string. */
                if (isColor) {
                    box.setStyle("backgroundColor", str);
                    textInput.errorString = "";
                } else {
                    box.setStyle("backgroundColor", StyleManager.NOT_A_COLOR);
                    textInput.errorString = "NOT A COLOR";
                }
            }
        ]]>
    </mx:Script>

    <mx:ApplicationControlBar dock="true">
        <mx:Label text="Color name:" />
        <mx:TextInput id="textInput" />
        <mx:Button label="isColorName()"
                fontFamily="_sans"
                click="button_click(event);" />
    </mx:ApplicationControlBar>

    <mx:Box id="box" width="100%" height="100%" />

</mx:Application>

View source is enabled in the following example.

If you want to add your own custom color aliases, you can use the StyleManager class’s registerColorName() method, as seen in the following snippet:

StyleManager.registerColorName('peter', 0x0BCDEF);
trace(StyleManager.isColorName('peter')); // true

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: