Question

I have an mxml page that has this tag:

<fx:Declarations>
        <mx:StringValidator id = "validator"
                            source = "{myTextInput}"
                            property = "text"
                            required = "true"
                            maxLength = "128"/>
<fx:Declarations>

I want to do the same in another page but build and add the validator dynamically using action script. I have this code for building the validator:

var lengthTextValidator:StringValidator  = new StringValidator();
lengthTextValidator.source = fieldTextInput;
lengthTextValidator.property = "text";
lengthTextValidator.required = true;

How can I finish the work and add the validator to the page? Thanks!

Was it helpful?

Solution

To add a UIComponent as a child of another UIComponent you can use addChild():

myComponent.addChild(myOtherUIComponent);

However, a validator is not a UIComponent or DisplayObject. It does not get added as a child to a page. If you are just replacing the fx:Declaration piece of an MXML file with an ActionScript piece that does the same thing, then you don't have to do much more.

I would make the lengthTextValidator a public, or protected, instance variable on the component:

public var lengthTextValidator:StringValidator  = new StringValidator();

That means the variable will be use within the component. Your original syntax without the public or private will either make a method specific variable that won't be accessible when the method is done executing or will put the variable in the internal namespace.

The rest of your code must go in a method. For an ActionScript class; you can put it in a constructor. Or for a MXML class you can put it in an initialize or creationComplete event handler.

lengthTextValidator.source = fieldTextInput;
lengthTextValidator.property = "text";
lengthTextValidator.required = true;

If you are putting the validator code in a separate class; then you'll have to import the class and create an instance of it:

import myPackage.MyClass;
public var myClass :MyClass = new MyClass();

Then you can access the validator by accessing the public variable on the component:

myClass.lengthTextValidator;

Finally; if you just want to move that snippet into an ActionScript file that is not a class; you can use the include directoive inside a fx:Script block:

<fx:Script><[[
 include "myASFile.as"
]]></fx:Script>

The last approach is unorthodox and not usually recommended.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top