我有一个文本字段,允许用户输入他们的年龄.我正在尝试使用JavaScript在此字段上进行一些客户端验证.我已经有了服务器端验证.但是,我似乎无法验证用户输入的实际整数.我目前正在尝试以下代码:
function IsValidAge(value) {
if (value.length == 0) {
return false;
}
var intValue = parseInt(value);
if (intValue == Number.NaN) {
return false;
}
if (intValue <= 0)
{
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
奇怪的是,我已将单个字符输入到文本框中,如"b",此方法返回true.如何确保用户只输入整数?
谢谢
kar*_*m79 131
var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
alert('I am an int');
...
}
Run Code Online (Sandbox Code Playgroud)
如果用户输入非负整数以外的任何内容,那绝对肯定会失败.
Pau*_*aul 31
对于真正的int检查,请使用:
function isInt(value) {
return !isNaN(parseInt(value,10)) && (parseFloat(value,10) == parseInt(value,10));
}
Run Code Online (Sandbox Code Playgroud)
许多int检查的问题是它们为1.0返回'false',这是一个有效的整数.此方法检查以确保float和int解析的值相等,因此对于#.00,它将返回true.
更新:
我将在评论中讨论两个问题,为未来的读者添加答案:
我的建议和做法是使用像Globalize.js这样的库来解析UI中的数值而不是浏览器实现,并仅对已知的"以编程方式"提供的值使用本机调用,例如从XML文档解析的字符串.
小智 13
使用isNaN(n)
即
if(isNaN(intValue))
Run Code Online (Sandbox Code Playgroud)
代替
if (intValue == Number.NaN)
Run Code Online (Sandbox Code Playgroud)
UPDATE
我有固定的有一个错误,并增加了一个名为变种的代码键存储键按下使用代码键代码以及其中,依赖浏览器.
var key = e.which || e.keyCode;
Run Code Online (Sandbox Code Playgroud)
谢谢Donald.McLean :)
如果要在输入时检查是否正在编写数字(并避免在输入字段中写入其他字符),可以使用此简单函数并定义允许的元素(这包括您要过滤的任何内容).通过这种方式,您不仅可以选择整数,还可以选择某组字符.该示例基于jQuery将其附加到输入字段.
$('#myInputField').keypress(function(e)
{
var key = e.which || e.keyCode;
if (!(key >= 48 && key <= 57) && // Interval of values (0-9)
(key !== 8) && // Backspace
(key !== 9) && // Horizontal tab
(key !== 37) && // Percentage
(key !== 39) && // Single quotes (')
(key !== 46)) // Dot
{
e.preventDefault();
return false;
}
});
Run Code Online (Sandbox Code Playgroud)
如果使用除定义之外的其他键,则不会出现在该字段中.而且因为Angular.js这些天变得越来越强大了.这是您可以在Web应用程序的任何字段中创建的指令:
myApp.directive('integer', function()
{
return function (scope, element, attrs)
{
element.bind('keydown', function(e)
{
var key = e.which || e.keyCode;
if (!(key >= 48 && key <= 57) && // Interval (0-9)
(key !== 8) && // Backspace
(key !== 9) && // Horizontal tab
(key !== 37) && // Percentage
(key !== 39) && // Single quotes (')
(key !== 46)) // Dot
{
e.preventDefault();
return false;
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
但是如果您想使用会发生什么,ng-repeat
并且您只需要在一定数量的字段中应用此指令.好吧,您可以将upper指令转换为准备接受true或false值的指令,以便能够决定哪个字段会受其影响.
myApp.directive('rsInteger', function() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
if (attrs.rsInteger === 'true') {
element.bind('keydown', function(e)
{
var key = e.which || e.keyCode;
if (!(key >= 48 && key <= 57) && // Interval (0-9)
(key !== 8) && // Backspace
(key !== 9) && // Horizontal tab
(key !== 37) && // Percentage
(key !== 39) && // Single quotes (')
(key !== 46)) // Dot
{
e.preventDefault();
return false;
}
});
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
要使用这个新指令,您只需要在这样的输入类型文本中执行此操作,例如:
<input type="text" rs-integer="true">
Run Code Online (Sandbox Code Playgroud)
希望它能帮到你.
归档时间: |
|
查看次数: |
90434 次 |
最近记录: |