Search code examples
actionscript-3flashpseudocode

Validate same values on change


Hello I have a problem with validating identical values in input boxes. Event called must be "on change" value of input box, but I have a problem with numbers.I want to write for example "17", but before there was value "1" already inputted in previous input box and it will report error because before we write 17 there is "1"- 7. So there is my question: is there a option to check identical values with this event type while dodging this error?

var textInput:Array = new Array();
for(var a:Number = 0;a < 2; a++){
    textInput[a] = new TextField();
    textInput[a].type = "input";
    textInput[a].y = 10+20*a;
    this.addChild(textInput[a]);
    textInput[a].addEventListener(Event.CHANGE, changeListener);
}

function changeListener (e:Event):void {
    if(Number(e.target.text)>22){
        e.target.text = "0";
    }
//problem area
    else{
        if(Number(textInput[1].text) == Number(textInput[0].text)){
            e.target.text = "0";
        }
    }
}

There is simple code with just 2 input boxes but in my project it more complex. How do define problem area to have possibility write "17" when we have "1" already in 1st input box.


Solution

  • You can't both allow and disallow the same thing at the same time, obviously.

    What you can do is validate the field on CHANGE and only mark it as valid or invalid (perhaps with some error styling) and on FOCUS_OUT you reset the text if it's not valid.

    Something like this:

    var valid:Boolean = true;
    input.addEventListener(Event.CHANGE, validate);
    input.addEventListener(FocusEvent.FOCUS_OUT, commit);
    
    function validate(e:Event):void {
        var input:TextField = e.currentTarget as TextField;
        var value:Number = Number(input.text);
        if(value > 22){
            valid = true;
            input.backgroundColor = 0xff0000; // error style
        }else{
            valid = false;
            input.backgroundColor = 0xffffff; // normal style
        }
    }
    
    function commit(e:FocusEvent):void {
        if(!valid){
            var input:TextField = e.currentTarget as TextField;
            input.text = "0";
            input.backgroundColor = 0xffffff; // normal style
        }
    }
    

    Also I would recommend that you encapsulate this stuff in a class that extends TextField.