Limiting character types in input fields with Actionscript 2

This is a small snippet that will force the input in a named input field (in our case it’s input_txt) to be numbers only.

function numOnlyMaxLen(maxLen, inputTxt, onSuccess){
 var theText = inputTxt.text;
 if(theText.length == maxLen){
  onSuccess();
 }
 var replacement = "";
 for(var i = 0; i < theText.length; i++){
  var curCode = theText.charCodeAt(i);
  if(curCode < 48 || curCode > 57)
   inputTxt.text = replacement;
  else
   replacement += theText.charAt(i);
 }
}

this.onEnterFrame = function(){
  numOnlyMaxLen(4, input_txt, function(){ trace('success') });
}

The numOnlyMaxLen function will call the function literal we pass as the final argument when we reach a limit of 4 characters. In our case it simply traces ‘success’ to the debug output window. Typically you would want to replace it with something like:

function(){ gotoAndPlay('onSuccess'); }

So on every frame update we loop through all the characters in the text field and check each and every one of them with charCodeAt which will return the decimal number of the character in the ASCII table. Anything below 48 and above 57 is not a number.

If we encounter a number we simply add it to the replacement variable, let’s pretend the input is 56, then we get 56 in the replacement variable. Now the user enters ‘j’ for instance into the text field. The 48/57 test will then return true and we will replace 56j with 56 through the inputTxt.text = replacement; line.

If the fps rate is set high enough in the movie settings (for instance 25) the user will never be able to see that there ever was a ‘j’ in the field before it is removed.

To limit other character types we could switch the (curCode < 48 || curCode > 57) part.

Only word characters: (curCode < 48 || (curCode > 57 && curCode < 65) || (curCode > 90 && curCode < 97) || curCode > 122).

No spaces: (curCode < 33)

Only letters: (curCode < 65 || (curCode > 90 && curCode < 97) || curCode > 122).

Check out for instance look up tables for an ASCII table and I think you can write your own custom filters with the help of the info above.

Related Posts

Tags: ,