This function is needed in many places, the headache is that the Chinese and English mixed in the time can not be processed, the following is my own through the Google query and write their own results:
First set Maxchars this property, which controls the text box input character length, in As3, a Chinese and a letter length is 1, but in fact a Chinese is 2 bytes, 1 English is a byte.
Set restrict = "a-za-z\u4e00-\u9fa5", which means that only uppercase and lowercase letters can be entered and Chinese
The above settings can guarantee the length and legality of the text, but cannot reach 12 characters or 6 Chinese (English and Mandarin inclusions) conditions, the following we add one step:
Gets the number of bytes in the string
Private Function Getstringbyteslength (str:string,charset:string): int
{
var bytes:bytearray = new ByteArray ();
Bytes.writemultibyte (str, charSet);
bytes.position = 0;
return bytes.length;
}
Add an event to the text input box:
Inputtxt.addeventlistener (Textevent.text_input, __nameinputevent);
Private Function __nameinputevent (e:textevent): void
{
if ((Getstringbyteslength (__nameinput.text, "gb2312") +
Getstringbyteslength (E.text, ' gb2312 ')) > __nameinput.maxchars)
{
E.preventdefault ();
Return
}
}
So it's done. The above is achievable under the Flash IDE, but in Flex, Textevent.text_input this event is not working and cannot be e.preventdefault (); So I continue to check the information, and then through the following methods, This functionality is implemented in Flex:
This is the component
<s:textinput x= "y=" id= "Txt_name" width= "" "enabled=" "true" changing= "__namechangingevent (event)"/>
This is the two properties that need to be set
Txt_name.restrict = "A-za-z\u4e00-\u9fa5";
Txt_name.maxchars = 12;
Here are the actions to use
/**
* Name Input Event
*
*/
protected function __namechangingevent (event:textoperationevent): void
{
if ((event.operation as Inserttextoperation) ==null)
{
Return
}
var input:string= (event.operation as inserttextoperation). Text;
if ((__getstringbyteslength (Txt_name.text, "gb2312") + __getstringbyteslength (input, ' gb2312 ')) > Txt_ Name.maxchars)
{
Event.preventdefault ();
}
}
/**
* Gets the number of bytes in the string
*/
Private Function __getstringbyteslength (str:string,charset:string): int
{
var bytes:bytearray = new ByteArray ();
Bytes.writemultibyte (str, charSet);
bytes.position = 0;
return bytes.length;
}