Javascript - 验证,仅限数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10713749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - validation, numbers only
提问by Anthony Do
I'm trying to get my login form to only validate if only numbers were inputted. I can it to work if the input is only digits, but when i type any characters after a number, it will still validate etc. 12akf will work. 1am will work. How can i get past this?
我试图让我的登录表单仅在输入数字时进行验证。如果输入只是数字,我可以工作,但是当我在数字后键入任何字符时,它仍然会验证等。12akf 将工作。凌晨 1 点将工作。我怎样才能克服这个?
Part of the Login
登录的一部分
<form name="myForm">
<label for="firstname">Age: </label>
<input name="num" type="text" id="username" size="1">
<input type="submit" value="Login" onclick="return validateForm()">
function validateForm()
{
var z = document.forms["myForm"]["num"].value;
if(!z.match(/^\d+/))
{
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
回答by apsillers
Match against /^\d+$/
. $
means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.
与 比赛/^\d+$/
。 $
表示“行尾”,因此在初始数字运行之后的任何非数字字符都会导致匹配失败。
Edit:
编辑:
RobG wisely suggests the more succinct /\D/.test(z)
. This operation tests the inverse of what you want. It returns true
if the input has anynon-numeric characters.
RobG 明智地提出了更简洁的建议/\D/.test(z)
。此操作测试您想要的逆操作。true
如果输入有任何非数字字符,则返回。
Simply omit the negating !
and use if(/\D/.test(z))
.
只需省略否定!
并使用if(/\D/.test(z))
.
回答by Max
here is how to validate the input to only accept numbers this will accept numbers like 123123123.41212313
这里是如何验证输入以只接受数字这将接受像 123123123.41212313 这样的数字
<input type="text"
onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
/>
and this will not accept entering the dot (.), so it will only accept integers
这将不接受输入点 (.),因此它只接受整数
<input type="text"
onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;"
/>
this way you will not permit the user to input anything but numbers
这样你就不会允许用户输入除了数字以外的任何东西
回答by kubio
This one worked for me :
这个对我有用:
function validateForm(){
var z = document.forms["myForm"]["num"].value;
if(!/^[0-9]+$/.test(z)){
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
回答by AtanuCSE
Late answer,but may be this will help someone
迟到的答案,但可能这会帮助某人
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Use will be like
使用会像
nn=document.forms["myForm"]["num"].value;
ans=isNumber(nn);
if(ans)
{
//only numbers
}
This ans was found from here with huge vote
这个答案是从这里以巨大的投票发现的
回答by Analyst
The simplest solution.
最简单的解决方案。
Thanks to my partner that gave me this answer.
感谢我的伙伴给了我这个答案。
You can set an onkeypressevent on the inputtextbox like this:
您可以在输入文本框上设置一个onkeypress事件,如下所示:
onkeypress="validate(event)"
onkeypress="validate(event)"
and then use regular expressions like this:
然后使用这样的正则表达式:
function validate(evt){
evt.value = evt.value.replace(/[^0-9]/g,"");
}
It will scan and remove any letter or sign different from number in the field.
它将扫描并删除与字段中的数字不同的任何字母或符号。
回答by J. Manis
Regular expressions are great, but why not just make sure it's a number before trying to do something with it?
正则表达式很棒,但为什么不在尝试使用它之前先确定它是一个数字呢?
function addemup() {
var n1 = document.getElementById("num1");
var n2 = document.getElementById("num2");
sum = Number(n1.value) + Number(n2.value);
if(Number(sum)) {
alert(sum);
} else {
alert("Numbers only, please!");
};
};
回答by KanimozhiPalanisamy
function ValidateNumberOnly()
{
if ((event.keyCode < 48 || event.keyCode > 57))
{
event.returnValue = false;
}
}
this function will allow only numbers in the textfield.
此函数将只允许文本字段中的数字。
回答by vinayakj
No need for the long code for number input restriction just try this code.
It also accepts valid int & float both values.
不需要数字输入限制的长代码,只需尝试此代码即可。
它还接受有效的 int 和 float 两个值。
Javascript Approach
Javascript 方法
onload =function(){
var ele = document.querySelectorAll('.number-only')[0];
ele.onkeypress = function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
return false;
}
ele.onpaste = function(e){
e.preventDefault();
}
}
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
jQuery Approach
jQuery 方法
$(function(){
$('.number-only').keypress(function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
The above answers are for most common use case - validating input as a number.
以上答案适用于最常见的用例 - 将输入验证为数字。
But to allow few special cases like negative numbers & showing the invalid keystrokes to user before removing it, so below is the code snippet for such special use cases.
但是为了允许一些特殊情况,例如负数并在删除之前向用户显示无效的击键,所以下面是此类特殊用例的代码片段。
$(function(){
$('.number-only').keyup(function(e) {
if(this.value!='-')
while(isNaN(this.value))
this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')
.split('').reverse().join('');
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
回答by Sudip Debnath
var elem = document.getElementsByClassName("number-validation"); //use the CLASS in your input field.
for (i = 0; i < elem.length; i++) {
elem[i].addEventListener('keypress', function(event){
var keys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0];
var validIndex = keys.indexOf(event.charCode);
if(validIndex == -1){
event.preventDefault();
}
});
}
回答by pawan sen
I think we do not accept long structure programming we will add everytime shot code see below answer.
我认为我们不接受长结构编程,我们将在每次拍摄代码时添加,请参见下面的答案。
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '');" >