TextInput的maxChars对于半角、全角字符个数验证

    TextInput的组件本身有maxChars属性来限制输入文字的个数,但不支持半角、全角。在网上查查了资料,终有所收获。下面放出例子,供大家参考:

 

<?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"> <fx:Script> <!--[CDATA[ import flash.desktop.Clipboard; import flash.desktop.ClipboardFormats; import flashx.textLayout.edit.SelectionState; import flashx.textLayout.operations.InsertTextOperation; import flashx.textLayout.operations.PasteOperation; import spark.events.TextOperationEvent; /** * changingHandler * 文字输入ing,全角半角文字个数验证 * * @param TextOperationEvent event * @return void * **/ protected function changingHandler(event:TextOperationEvent):void { var target:TextInput = event.currentTarget as TextInput; if (target.maxChars <= 0) return; //原始文本 var oldText:String = target.text; //新追加的文本 var addText:String; //选中文字的长度(将要被覆盖的文字) var delLen:int; //文字总长度 var totalLen:int; var insertOp:InsertTextOperation; var pasteOp:PasteOperation; var selectState:SelectionState; if (event.operation is InsertTextOperation) { //文本插入 insertOp = event.operation as InsertTextOperation; //获取新追加的文本 addText = insertOp.text; //获取选中文字的对象 selectState = insertOp.deleteSelectionState; delLen = selectState ? getByteLenByStr(oldText.substring(selectState.absoluteStart, selectState.absoluteEnd)) : 0; //总长度 totalLen = getByteLenByStr(oldText) + getByteLenByStr(addText) - delLen; if (totalLen > target.maxChars) event.preventDefault(); } else if (event.operation is PasteOperation) { //文本粘帖 pasteOp = event.operation as PasteOperation; //获取粘帖的文本 addText = Clipboard.generalClipboard.getData(ClipboardFormats.TEXT_FORMAT) as String; //获取选中文字的对象 selectState = pasteOp.originalSelectionState; delLen = selectState ? getByteLenByStr(oldText.substring(selectState.absoluteStart, selectState.absoluteEnd)) : 0; //总长度 totalLen = getByteLenByStr(oldText) + getByteLenByStr(addText) - delLen; if (totalLen > target.maxChars) event.preventDefault(); }//if event.operation end } /** * getByteLenByStr * 获取字符串字节的长度(半角1字节、全角2个字节) * * @param String val * @param String charSet * @return uint * **/ public function getByteLenByStr(val:String, charSet:String = "utf8"):uint { if (!val) return 0; var byteArr:ByteArray = new ByteArray(); byteArr.writeMultiByte(val, charSet); byteArr.position = 0; return byteArr.length; } ]]--> </fx:Script> <fx:Declarations> </fx:Declarations> <s:layout> <s:VerticalLayout paddingTop="10" paddingLeft="10"/> </s:layout> <s:Label text="关于文字输入半角、全角文字长度验证maxChars"/> <s:HGroup verticalAlign="bottom"> <s:TextInput changing="changingHandler(event)" width="100" maxChars="10"/> <s:Label text="半角10个、全角5个文字限制"/> </s:HGroup> </s:Application>

你可能感兴趣的:(String,function,application,import,library,encoding)