Html 检查输入是数字还是字母javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18042133/
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
Check if input is number or letter javascript
提问by Greg Peckory
I'm using forms in HTML and javascript. I would like an alert to pop up only if the user inputs a LETTERand clicks submit
.
我在 HTML 和 javascript 中使用表单。我希望仅当用户输入LETTER并单击时才会弹出警报submit
。
So I have the HTML code:
所以我有 HTML 代码:
<form name="myForm" action="" onsubmit="return checkInp()" method="post">
First name: <input type="text" name="age">
<input type="submit" value="Submit">
And the javascript code:
和 javascript 代码:
function checkInp()
{
var x=document.forms["myForm"]["age"].value;
if (x consists of any letters) // this is the code I need to change
{
alert("Must input numbers");
return false;
}
}
回答by Bat_Programmer
You can use the isNaN function to determine if a value does not convert to a number. Example as below:
您可以使用 isNaN 函数来确定值是否未转换为数字。示例如下:
function checkInp()
{
var x=document.forms["myForm"]["age"].value;
if (isNaN(x))
{
alert("Must input numbers");
return false;
}
}
回答by Kim Kling
Use Regular Expressionto match for only letters. It's also good to have knowledge about, if you ever need to do something more complicated, like make sure it's a certain count of numbers.
使用正则表达式只匹配字母。如果您需要做一些更复杂的事情,例如确保它是一定数量的数字,那么了解相关知识也很好。
function checkInp()
{
var x=document.forms["myForm"]["age"].value;
var regex=/^[a-zA-Z]+$/;
if (!x.match(regex))
{
alert("Must input string");
return false;
}
}
Even better would be to deny anything but numbers:
更好的是否认除数字之外的任何内容:
function checkInp()
{
var x=document.forms["myForm"]["age"].value;
var regex=/^[0-9]+$/;
if (x.match(regex))
{
alert("Must input numbers");
return false;
}
}
回答by mael
You could use the isNaNFunction. It returns true if the data is not a number. That would be something like that:
您可以使用isNaN函数。如果数据不是数字,则返回 true。那将是这样的:
function checkInp()
{
var x=document.forms["myForm"]["age"].value;
if (isNaN(x)) // this is the code I need to change
{
alert("Must input numbers");
return false;
}
}
Note: isNan considers 10.2 as a valid number.
注意:isNan 将 10.2 视为有效数字。
回答by Crypters
Just find the remainder by dividing by 1, that is x%1. If the remainder is 0, it means that x is a whole number. Otherwise, you have to display the message "Must input numbers". This will work even in the case of strings, decimal numbers etc.
只需找到除以 1 的余数,即 x%1。如果余数为 0,则表示 x 是整数。否则,您必须显示消息“必须输入数字”。即使在字符串、十进制数等的情况下,这也能工作。
function checkInp()
{
var x = document.forms["myForm"]["age"].value;
if ((x%1) != 0)
{
alert("Must input numbers");
return false;
}
}
回答by Deepak Gangore
you can use isNaN(). it returns true when data is not number.
你可以使用 isNaN()。当数据不是数字时返回真。
var data = 'hello there';
if(isNaN(data)){
alert("it is not number");
}else {
alert("its a valid number");
}
回答by Masoud Nazari
Try this:
尝试这个:
if(parseInt("0"+x, 10) > 0){/* x is integer */}
回答by str8up7od
I know this post is old but it was the first one that popped up when I did a search. I tried @Kim Kling RegExp but it failed miserably. Also prior to finding this forum I had tried almost all the other variations listed here. In the end, none of them worked except this one I created; it works fine, plus it is es6:
我知道这篇文章很旧,但它是我搜索时出现的第一个。我尝试过 @Kim Kling RegExp 但它失败了。同样在找到这个论坛之前,我已经尝试过这里列出的几乎所有其他变体。最后,除了我创建的这个之外,它们都没有工作;它工作正常,而且它是 es6:
let regex = new RegExp(/[^0-9]/, 'g');
let x = document.forms["myForm"]["age"].value;
if (x.match(regex)) {
alert("Must be a valid number");
return
}
回答by Vikas Bansal
I think the easiest would be to create a Number
object with the string and check if with the help of isInteger
function provided by Number
class itself.
我认为最简单的方法是Number
用字符串创建一个对象,并在类本身isInteger
提供的函数的帮助下检查是否Number
。
Number.isInteger(Number('1')) //true
Number.isInteger(Number('1 mango')) //false
Number.isInteger(Number(1)) //true
Number.isInteger(Number(1.9)) //false
回答by Ram Patra
A better(error-free) code would be like:
更好(无错误)的代码如下:
function isReallyNumber(data) {
return typeof data === 'number' && !isNaN(data);
}
This will handle empty strings as well. Another reason, isNaN("12")
equals to false
but "12"
is a string and not a number, so it should result to true
. Lastly, a bonus linkwhich might interest you.
这也将处理空字符串。另一个原因,isNaN("12")
等于false
但是"12"
是一个字符串而不是一个数字,所以它应该导致true
. 最后,一个您可能感兴趣的奖励链接。
回答by visibleman
function isNumber(data){
data = data +"e1"; // Disallow eng. notation "10e2"+"e1" is NaN
var clean = parseFloat(data,10) / data ; // 1 if parsed cleanly
return ( data==0 || clean && (data/data) === 1.0); // Checks for NaN
}
function isInteger(data){
data = data +"e1"; // Disallow eng. notation "10e2"+"e1" is NaN
var clean = parseInt(data,10) / data ; // 1 if parsed cleanly
return (data==0 ||clean && (data%1) === 0); // Checks For integer and NaN
}
//Expected pass
console.log(isNumber("0"))
console.log(isNumber("-0.0"))
console.log(isNumber("+0.0"))
console.log(isNumber(0))
console.log(isNumber(-0.0))
console.log(isNumber(+0.0))
console.log(isNumber(1))
console.log(isNumber(-10.0))
console.log(isNumber(+1000.000001))
console.log(isNumber(1))
console.log(isNumber(-10.0))
console.log(isNumber(+1000.000001))
//Expected fail
console.log(isNumber("FF"))
console.log(isNumber("1e1"))
console.log(isNumber("seven"))