Regular expressions for input restriction in AS3
August 22, 2009
Regular expressions is one of the useful things that Adobe has integrated in Actionscript 3. Regular expressions simplifies the way you do the validation of email, date, url ...
Nonetheless if you want to use regular expressions in Actionscript 3 to restrict the input in a textfield, you will notice a difference in the syntax for Adobe has come up with an own one, similar to regular expressions.
The solution therefore is to implement an interception of characters typed before they are displayed. Then you can start using regular expressions.
Reference
http://www.adobe.com/go/AS3_regex_overview
Function
function restrictInput( input:String, pattern:RegExp ):String
{
var result:Object = pattern.exec( input );
var newInput:String = "";
for ( var i:int = 0; i < input.length; i++ )
{
var char:String = input.charAt( i );
if ( pattern.test( char ) )
{
newInput += char;
}
}
return newInput;
}
Usage
restrictInput( input, /([A-Z a-z 0-9 \t\r\n\v\f, ?!])/ );
Leave a Reply