与 TheDarklins 的答案非常相似,但更优雅一些。实际上会使_tf.restrict 过时,但我仍然建议使用它。
_tf.addEventListener(TextEvent.TEXT_INPUT, _onTextInput_validate);
这里的这两个事件侦听器都执行相同的EXACT功能。对于那些喜欢较小代码的人来说,一个是用一行编写的。另一种是为那些喜欢逐行查看正在发生的事情的人。
private function _onTextInput_validate(__e:TextEvent):void
{
if ( !/^\d{1,2}(?:\.(?:\d)?)?$/.test(TextField(__e.currentTarget).text.substring(0, TextField(__e.currentTarget).selectionBeginIndex) + __e.text + TextField(__e.currentTarget).text.substring(TextField(__e.currentTarget).selectionEndIndex)) ) __e.preventDefault();
}
对于事件监听器的更细分版本
private function _onTextInput_validate(__e:TextEvent):void
{
var __reg:RegExp;
var __tf:TextField;
var __text:String;
// set the textfield thats causing the event.
__tf = TextField(__e.currentTarget);
// Set the regular expression.
__reg = new RegExp("\\d{1,2}(?:\\.(?:\\d)?)?$");
// or depending on how you like to write it.
__reg = /^\d{1,2}(?:\.(?:\d)?)?$/;
// Set all text before the selection.
__text = __tf.text.substring(0, __tf.selectionBeginIndex);
// Set the text entered.
__text += __e.text;
// Set the text After the selection, since the entered text will replace any selected text that may be entered
__text += __tf.text.substring(__tf.selectionEndIndex);
// If test fails, prevent default
if ( !__reg.test(__text) )
{
__e.preventDefault();
}
}
我必须允许 xx. 作为有效响应,否则您需要输入 123 然后返回一个空格并输入 。 12.3。那不是很好。所以12. 现在在技术上是有效的。