问题
I use a TextInput component of Flex 4.5 to enter some text in English. I use the restrict attribute to ... restrict the keyboard input to characters a-zA-Z only. The problem is that if i copy/paste a word in another language, i can then paste it into the TextInput component. Is there a way to avoid that? If no, how can i validate the input against a specified language?
I found out that the unicode set of Chinese+ language symbols is \u4E00 to \u9FFF. So i write the following:
var chRE:RegExp = new RegExp("[\u4E00-\u9FFF]", "g");
if (inputTI.text.match(chRE)) {
trace("chinese");
}
else {
trace("other");
}
But if i type in the TextInput the word 'hello' then it validates...What is the error?
Since i cannot (my fault? or a bug?) use unicode range with RegExp, i wrote the following function to check if a word is in Chinese and that's it.
private function isChinese(word:String):Boolean
{
var wlength:int = word.length;
for (var i:int = 0; i < wlength; i++) {
var charCode:Number = word.charCodeAt(i);
if (charCode <= 0x4E00 || charCode >= 0x9FFF) {
return false;
}
}
return true;
}
回答1:
The String.match()
method returns an array which will always test to true, even if it's empty (see docs here: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/String.html#match%28%29)
Use the RegExp.test()
method instead to see if it matches:
// Check your character ranges:
//var chRE:RegExp = new RegExp("[\u4E00-\u9FFF]", "g"); // \u9FFF is unrecognised and iscausing issues.
var chRE:RegExp = new RegExp("[\u4E00]+", "g"); // This works.
if (chRE.test(inputTI.text)) {
trace("chinese");
}
else {
trace("other");
}
You'll need to check the character ranges too - I couldn't get it to match with \u9FFF in the regex.
来源:https://stackoverflow.com/questions/7561916/restrict-input-to-a-specified-language