JS_Alert 发表于 2013-12-29 17:54:05

Lua中能否限制输入到富文本框的内容?

在platform.apiLevel='2.0'环境下,我想限制一个富文本框只能输入浮点数(这样做的原因是其它字符可能导致一些数学函数出错),应该怎样限制?
注意,错误处理表正被使用。

wtof1996 发表于 2013-12-29 21:43:49

使用registerFilter即可
例如以下代码只可以输入字母和数字:

--以下代码来自我正在开发的Lua字符串扩展库,详见https://github.com/wtof1996/TI-Lua_String_Library_Extension/

--[[
    TI-Lua String Library Extension ---- ctype(non assert version)
    Copyright 2013 wtof1996

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
]]--
ctype = {};
--The exceptiontable
ctype.exception = {["invChar"] = "ctype:invalid character", ["invType"] = "ctype:invalid type", ["longString"] = "ctype:the string is too long"};

--This private function is used to check input & convert all kinds of input into number.
function ctype.CheckInput(input)
    if(type(input) == "number") then
      if((input > 0x7F) or (input < 0) or (math.ceil(input)) ~= input)then return nil, ctype.exception.invChar end;
      return input;
    elseif(type(input) == "string") then
      if(#input > 1) then return nil, ctype.exception.longString end;
      local res = input:byte();
      if((res > 0x7F) or (res < 0))then return nil, ctype.exception.invChar end;
      return res;
    else
      return nil, ctype.exception.invType;
    end
end

--Public function
function ctype.isalnum(char)
    local res, err = ctype.CheckInput(char);
    if(err ~= nil) then return nil, err end;

    if( ((res >= 0x30) and (res <= 0x39)) or
      ((res >= 0x41) and (res <= 0x5A))or
      ((res >= 0x61) and (res <= 0x7A))
       ) then return true, nil end;
    return false, nil;
end

--EOF
TextBox = D2Editor.newRichText();
TextBox:move(20, 20)
TextBox:resize(100, 100)
TextBox:setBorder(1);
TextBox:registerFilter{
    charIn = function (char)
                local ret, err = ctype.isalnum(char);
                if(err == nil) then
                  if(ret == true) then return false end; --如果输入的是字母或者数字那么我们允许传递给文本框
                end
                return true;--否则不允许
             end
}


JS_Alert 发表于 2014-1-1 00:53:47

wtof1996 发表于 2013-12-29 21:43 static/image/common/back.gif
使用registerFilter即可
例如以下代码只可以输入字母和数字:



谢谢 确实没想到。
页: [1]
查看完整版本: Lua中能否限制输入到富文本框的内容?