Create a Password Masking Class in ActionScript 3.0
Password fields allow you to create a field, similar to a text field, which users can type into. A password field however, causes everything show up as asterisks (*) so onlookers cannot see what is being typed.
In this tutorial, we’ll create a Static Class that will convert an Input TextField to an iPhone-like password field.
Step 1: Brief Overview
We’ll make use of the static attribute in ActionScript 3.0 to declare a Class that won’t need to be instantiated to be used, this way we can call its methods without creating an object using the new operator.
Our Class will create a Timer that will replace the characters of the target TextField to any given character in the specified time.
Step 2: Starting
Open Flash and create a new Flash File (ActionScript 3).

Set the stage size to 600×300 and add a gray linear background (#EEEEEE, #DDDDDD).

Step 3: Interface
Let’s add some graphic details to our application.
Select the Rectangle Tool (R), create a 600x50px rectangle and fill it with #222222.

Create a Static TextField to add a title. I used Helvetica Bold 21pt as TextFormat.

Use the Rectangle Primitive Tool to create a 200x30px rectangle (#AAAAAA) and change the radius to 6.00. Duplicate this shape (Cmd + D), resize it to 198x28px, change its color to #EEEEEE and center it in the previous shape.
Add some text to label the field.

This will complete the graphic part.
Step 4: Password Field
We will create an Input TextField that we’ll use to get the user’s input, and to specify a target in our password masking class.
Select the Text Tool (T) and place an Input TextField in the background we created before. Set its instance name to passField.

Step 5: ActionScript!
Create a new ActionScript Document and save it as iPass.as. This will be our static class.

Step 6: Required Classes
The classes we’ll need. For specific information please refer to the Flash help (F1).
package classes
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
Step 7: Extending the Class
We’re going to use Sprite specific methods and properties so we extend using the Sprite Class.
public class iPass extends Sprite
{
Step 8: Variables
These are the variables we will use, explained in the comments. Notice that the variables are declared as static to have access without an instance.
public static var pass:String = ""; //This will store the original password for any use public static var target:TextField; //The TextField to mask private static var regExp:RegExp = /./g; //A Regular Expresion, looks for ALL the characters public static var timer:Timer = new Timer(1000); //Timer object, will execute every second, when called
Step 9: Main Function
This is the method we will call to use the class.
public static function maskTextField(t:TextField):void //We need a parameter that will specify the target TextField
{
target = t;
addListeners();
}
Step 10: Replace Function
This is the function that will replace the characters in the target field.
private static function replaceOnTime(e:TimerEvent):void
{
target.text = target.text.replace(regExp, "•"); //Replaces all the characters in the textfield with "•"
timer.stop(); //Stops the timer when the characters are replaced
}
Step 11: Start Timer
This function will start the Timer when the target textfield is in focus and a key is pressed.
private static function startTimer(e:KeyboardEvent):void
{
/* If the timer is not running, start it, else, reset timer, replace all characters but last, and run timer again */
!timer.running ? timer.start() : timer.reset(); var msk:String = target.text.substring(0, target.length - 1); target.text = msk.replace(regExp, "•") + String.fromCharCode(e.charCode);timer.start();
/* Filters valid keys, from a to Z */
for (var i:int = 65; i < 123; i++)
{
if (e.charCode == i)
{
pass += String.fromCharCode(i);
}
}
if (e.keyCode == Keyboard.BACKSPACE)
{
pass = pass.substring(0, pass.length - 1); //If delete is pressed, delete last char
}
}
Step 12: Listeners
Adds the listeners to the Timer and TextField objects.
private static function addListeners():void
{
timer.addEventListener(TimerEvent.TIMER, replaceOnTime);
target.addEventListener(KeyboardEvent.KEY_UP, startTimer);
}
Step 13: Main Class
This class will call the iPass static class and pass the TextField in stage as a parameter.
Create a new ActionScript Document and save it as Main.as.
package classes
{
import classes.iPass;
import flash.display.Sprite;
public class Main extends Sprite
{
public function Main():void
{
iPass.maskTextField(passField); //Calls the iPass class
}
/*private function getPassword():void
{
trace(iPass.pass); //An example of how to get the password
}*/
}
}
Step 14: Document Class
Go back to the .Fla file and in the Properties Panel add classes.Main in the Class field to make it the Document Class.
Conclusion
You have now created a password masker class and learned how to create and use a Static Class – experiment with its advantages!
Thanks for reading!


XML Photography Template V2 only $40.00 
Thanks, but does the real string got lost? So if you check the entry, you’ll got something like ******* and not the real string?
@Phil, I think it stores it in the ‘pass’ variable, check step 8.
Very sleek overall, but I find if you type to quickly it appends letters to the end. I was typing ‘password’ and ending up with 9 asterisks.
you’re right, got it
passfield.displayAsPassword = true;
Why go around the block if you could go straight to town… There’s like an textfield property: “displayAsPassword”. I think that would save A LOT of time !
In AS3 language:
var textField:TextField = new TextField();
textField.displayAsPassword = true;
You dont even need the script for this… You can define the Input text type as password, which automatically creates each letter as an asterik as you type. You’ll never see any letters displayed on screen this way.
is this for slow typers only?
“iPhone-like password field”!? Ever used an (Sony) Ericsson before? :p
Glad you shared this. Would love to see someone take on encryption from the Flash TextField to a backend language like PHP. Or a login screen that creates a session for another page. I currently am using a strategy from book PHP 5 for Flash where you create a session on one page and it redirects to PHP page.
He’s just trying to show us how to change that “*” in most passwords to the dot, in this case an iPhone style. It’s useful actually, sometimes I can be really picky at things like this.
Pretty bad…
Setting a field just like a password field doesn’t allow you to see your own input, and thus, if you mistakenly push two keys, or a wrong one, you wouldn’t notice … this way, you can actually see what you are typing, and then gets converted to dots. (or asterisxs anyway)
I like the concept but the code needs improvement. When I tested the demo out I started typing slowly and it worked fine. I then backspaced everything paused for a second and it added a dot in the field even though I had no characters typed. So if anything that needs improvement is the delay for the characters to change to dots. Maybe check to see if there is even a character there first. To solve the issue of fast typing, if another key is pressed just override the delay and automatically set the previous character as a dot.
Cursor position on left side… which is not good..
So, do I get real money if I write those kind of tutorials?
Full of bugs,
if i click “home”, “end”, or “arrow keys”
the password got deleted 1 by 1
this tutorial is totally useless
I ask you Carlos, whats the point?
just use the password option on the text box field.
I think everyone is used to retyping the passowrd if its wrong and if you are any good you will have a check function to validate the password anyway.
Active tuts your standards are starting to slip….
I just don’t understand how you even felt satisfied posting unfinished work. It just doesn’t make sense. Why bother putting it up if you know it doesn’t work? You had to have known about the bugs.. unless you neglected to test it at all.
It`s buggy a little.
Here is update from me ;)
_________________________________________________________________________________________________________________________
package classes{
import flash.display.Sprite;
import flash.text.TextField;
import flash.utils.Timer;
import flash.events.*;
public class iPass extends Sprite {
public static var target:TextField;
private static var regExp:RegExp=/./g;
private static var restictExp:String=’a-z A-Z 0-9′;
public static var timer:Timer
public static var pass:String=”;
public static function maskTextField(t:TextField,delay:Number=500):void {
timer=new Timer(delay);
target=t;
target.restrict=restictExp;
timer.addEventListener(TimerEvent.TIMER, replaceOnTime);
target.addEventListener(TextEvent.TEXT_INPUT, startTimer);
}
private static function replaceOnTime(event:TimerEvent):void {
target.text=target.text.replace(regExp,”•”);
timer.stop();
}
private static function startTimer(event:TextEvent):void {
pass+=event.text;
var str:String=target.text;
if (timer.running) {
timer.reset();
}
timer.start();
}
}
}
_____________________________________________________________
———————————————————————————————————-
And if you want to declare max number of nonhidden characters
_____________________________________________________________
package classes{
import flash.display.Sprite;
import flash.text.TextField;
import flash.utils.Timer;
import flash.events.*;
public class iPass extends Sprite {
public static var target:TextField;
private static var regExp:RegExp=/./g;
private static var restictExp:String=’a-z A-Z 0-9′;
private static var maxWait:int=1;
public static var timer:Timer
public static var pass:String=”;
public static function maskTextField(t:TextField,delay:Number=500,waitLength:int=0):void {
timer=new Timer(delay);
maxWait=waitLength>0?waitLength-1:0;
target=t;
target.restrict=restictExp;
timer.addEventListener(TimerEvent.TIMER, replaceOnTime);
target.addEventListener(TextEvent.TEXT_INPUT, startTimer);
}
private static function replaceOnTime(event:TimerEvent):void {
target.text=target.text.replace(regExp,”•”);
timer.stop();
}
private static function startTimer(event:TextEvent):void {
pass+=event.text;
var str:String=target.text;
var lastChr:int=target.caretIndex-maxWait;
target.text=str.substring(0,lastChr).replace(regExp,”•”)+str.substring(lastChr);
if (timer.running) {
timer.reset();
}
timer.start();
}
}
}
Dood last class is the desired result.
I get 15 errors with that last class. The majority being synthax. Hmmm.
Scratch that. You need to manually put in the quotation marks and aposterphies. A simple copy-paste gives odd characters. Great work!
Hello, can someone explain to e how i path 2 files in my chat application that i develop by flash because
have two files “iPass” and “Main” i dont know how i run both of them inside flash builder
thanks
The developer that has written this tutorial really do know what he’s up to. As a staring point he clames that the iPass class needs to extend Sprite (“We’re going to use Sprite specific methods and properties so we extend using the Sprite Class.”), which is totally not true, the code that he have written in that class is not at any point dependent of the Sprite class or any DisplayObject.
Secondly using a Static class structure to manage one single password input at a time, is quite pointless. A better approach would be using a instance based class that actually can be added to the display list, etc. extend the TextField class or a Sprite class and wrap around a TextField instance. using the approach mention will give you a unlimited amount of instances that can be managed at anytime.
And what this Tutorial is event better at is memory leakage, the code written does not clean up the event listeners to the old textfield when assigning a new TextField (mark these words) as the current target.
Even if all of the following weaknesses above is corrected, it’s quite hard to implement a solution that works correctly. This tutorial fall very short but even in this category as it’s full of glitches that is very obvious to even the end-user directly. To a fully functional password input you should also want to take the user’s cut-copy-paste actions into account.
Played around with that, added a key listener for backspace/delete which was an issue. Should be pretty tight now.
package {
import flash.events.KeyboardEvent;
import flash.events.TextEvent;
import flash.events.TimerEvent;
import flash.text.TextField;
import flash.utils.Timer;
public class HidePass extends Sprite {
public var pass:String = “”;
private var _target:TextField;
private var _regExp:RegExp = /./g;
private var _timer:Timer;
public function HidePass (t:TextField, $delay:uint = 500) : void {
_timer=new Timer($delay);
_target=t;
}
private function replaceOnTime(event:TimerEvent):void {
_target.text = _target.text.replace(_regExp, “•”);
_timer.stop();
}
private function _startTimer (event:TextEvent) : void {
pass += event.text;
if (_timer.running) _timer.reset();
_timer.start ();
}
public function setActive ($boo:Boolean) : void {
if ($boo) {
_target.addEventListener(KeyboardEvent.KEY_UP, _onKeyUp);
_timer.addEventListener(TimerEvent.TIMER, replaceOnTime);
_target.addEventListener(TextEvent.TEXT_INPUT, _startTimer);
} else {
_target.addEventListener(KeyboardEvent.KEY_UP, _onKeyUp);
_timer.addEventListener(TimerEvent.TIMER, replaceOnTime);
_target.addEventListener(TextEvent.TEXT_INPUT, _startTimer);
}
}
private function _onKeyUp ($e:KeyboardEvent) : void {
if ($e.keyCode == 8) {
pass = pass.slice(0, pass.length-1);
if (_target.text.length < 1) pass = "";
}
}
}
}
.
Forgot to mention changed to non static as was an issue when several passfields at the same time. Needs the class declared. Cheers.