在更改时验证相同的值

Validate same values on change

您好,我在验证输入框中的相同值时遇到问题。调用的事件必须是输入框的 "on change" 值,但我有一个问题 numbers.I 想写例如“17”,但在上一个输入框已经输入值“1”之前,它会报告错误,因为在我们写 17 之前有“1”- 7。所以我的问题是:是否有一个选项可以在避免此错误的同时检查与此事件类型相同的值?

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";
        }
    }
}

有一个只有 2 个输入框的简单代码,但在我的项目中它更复杂。当我们在第一个输入框中已经有“1”时,如何定义问题区域有可能写“17”。

显然,您不能同时允许和禁止同一件事。

您可以做的是验证 CHANGE 上的字段,仅将其标记为有效或无效(可能带有一些错误样式),而在 FOCUS_OUT 上,如果文本无效则重置文本。

像这样:

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
    }
}

此外,我建议您将这些内容封装在扩展 TextField.

的 class 中