Internet Explorer 7Internet Explorer 6.0IEXHTMLWebForms.NET 2.0中级开发Visual StudioJavascriptWindows.NETASP.NETC#
ASP.NET 的 NumericTextBox






4.38/5 (6投票s)
一个 ASP.NET 控件,允许用户仅输入数字。
引言
所有应用程序都必须是“愚蠢的证明”,因此我们正在创建检查用户输入的控件,而这正是其中之一。 在这个网站上,我只找到了 Windows Forms 的解决方案,所以我展示了我的 ASP.NET 解决方案。
最初,有一个具有这些功能的控件的想法
- 可选输入负数
- 可选输入小数或整数
- 从区域设置中选择或自动加载小数点分隔符
- 处理 Ctrl + V
- 跨浏览器兼容性
解决方案 - 关注点
- 处理所有字符 - 最后,我选择了“
onkeypress
”事件,因为如果在此事件上触发的函数返回false
,则该字符将不会插入到文本框中。 - 过滤字符 - 所有字符都有一个
keyCode
,所以我必须列出允许的字符(通过数字键盘按钮插入的数字与通过键盘上一行插入的数字具有不同的代码); 此外,必须允许功能键,如 Shift、BackSpace、Delete 和箭头 - 只需要几分钟的测试。 - 可选的负号 - 负号必须是该值的第一个字符,因此我必须检查光标位置 - 这意味着兼容性问题; 最后,我这样解决了这个问题
function getCursorPosition(txt)
{
if(document.selection) // IE
{
txt.focus();
var oSel = document.selection.createRange();
oSel.moveStart('character', -txt.value.length);
return oSel.text.length;
}
else(txt.selectionStart) // Firefox etc.
return txt.selectionStart;
}
private char GetDecimalSeparatorFromLocale()
{
return (System.Globalization.CultureInfo.CurrentUICulture.
NumberFormat.NumberDecimalSeparator.ToCharArray())[0];
}
- 不能是第一个字符
- 不能在负号之后
- 该值中只能有一个小数点分隔符
这段“漂亮的”代码检查了所有这些条件
if(txt.value.replace("-", "").length > 0 &&
getCursorPosition(txt) > 0 &&
txt.value.indexOf(decimalSeparator) == -1 && decimals)
return true;
else
return false;
break;
onchage
”事件中,会触发一个检查函数。 此函数检查所有字符以查看它们是否被允许,并且仅保留数字,以及可选的负号和小数点字符。function CheckString(txt, negative, decimals, decimalSeparator)
{
var res = "";
var decimalSeparatorCount = 0;
for(i = 0; i < txt.value.length; i++)
{
if(i == 0 && txt.value.charAt(0) == "-" && negative)
res = "-";
else
{
if(IsNumber(txt.value.charAt(i)))
// IsNumber function returns true if the char is 0-9
res += txt.value.charAt(i);
else
{
if(txt.value.charAt(i) == decimalSeparator &&
decimalSeparatorCount == 0 && decimals)
{
res += txt.value.charAt(i);
decimalSeparatorCount++;
}
}
}
}
txt.value = res;
}
- 如前所述,IE 6、7 在获取光标位置方面存在问题
- Safari 为功能键返回不同的 keyCode - 为所有键返回 0,但数字和其他不允许字符的代码运行良好
- 已测试的浏览器:IE 6、7、Opera 9、Firefox 2、Safari for Windows beta 3、Netscape 8(与 Firefox 相同,它使用 Gecko 引擎)
Using the Code
使用此代码很简单,因为它继承了 TextBox
类,因此您可以使用验证器并在 Text
属性中访问该值。
<cp:NumericTextBox AllowNegative="true" AllowDecimals="true"
runat="server" ID="NumericTextBox1" />
此控件主要基于 JavaScript,因此它可以很容易地用于其他平台,例如 PHP、JSP 等,以及 ASP.NET; 如果您翻译了它,请告诉我。