javascript 如何使用javascript检查文本框中的第一个字符是否为数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15737763/
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
how to use javascript to check if the first character in a textbox is a number?
提问by Dora
I'm making a simple form and having a textbox for street address.... All I want to do is check if the first value entered is a number or not.
我正在制作一个简单的表格,并有一个街道地址的文本框......我想要做的就是检查输入的第一个值是否是数字。
How can I do it?
我该怎么做?
if(document.forms[0].elements[2].value.
that is all I have now but I'm not sure what I should add to it to check the first character only.
这就是我现在所拥有的,但我不确定我应该添加什么来检查第一个字符。
回答by vdua
As you said in your question you want to check for the first character only, you can use charAtfunction for string to check whether the first character is from 0 to 9 or any other check you want for the first character
正如您在问题中所说,您只想检查第一个字符,您可以对字符串使用charAt函数来检查第一个字符是否从 0 到 9 或您想要的任何其他检查第一个字符
Possible solution
可能的解决方案
var firstChar = document.forms[0].elements[2].value.charAt(0);
if( firstChar <='9' && firstChar >='0') {
//do your stuff
}
回答by Jordan Michael Rushing
This can simply use isNaN
. Just put a bang before it to check if it is a number, instead of isNaN
's normal use of checking if it isn't a number, like so:
这可以简单地使用isNaN
. 只需在它之前放一个 bang 来检查它是否是数字,而不是isNaN
正常使用检查它是否不是数字,如下所示:
var val = document.forms[0].elements[2].value;
if (!isNaN(val.charAt(0))){ //If is a number
//Stuff
}
This also goes with numbers as strings, so need to worry about quotes or any of that hoo ha.
这也适用于作为字符串的数字,因此需要担心引号或任何 hoo ha。
回答by Havenard
You can use if (document.forms[0].elements[2].value.match(/^\d+/))
to check if the beginning of the field is composed by numbers.
您可以使用if (document.forms[0].elements[2].value.match(/^\d+/))
来检查字段的开头是否由数字组成。
It will match for:
它将匹配:
0 - valid
1 - valid
1a - valid
1 a - valid
1234567 - valid
a - invalid
a1 - invalid
Literally anything that start with numbers.
任何以数字开头的东西。
You can extend its functionality to if (document.forms[0].elements[2].value.match(/^\d+ +.+/))
您可以将其功能扩展到 if (document.forms[0].elements[2].value.match(/^\d+ +.+/))
In this form it will now require that its a number, plus one or more spaces, followed by anything else.
在这种形式中,它现在要求它是一个数字,加上一个或多个空格,然后是其他任何内容。
0 - invalid
1 - invalid
1(space) - invalid
1 1 - valid
1 a - valid
12345 abcdef - valid
Read more about Regular Expressionsto elaborate complexier checkings.
阅读有关正则表达式的更多信息以详细说明更复杂的检查。
But remember first that not every address has numbers, and most countries in the world don't use this format of writing addresses. As for the address field, I believe you should leave it open to be written in however format the user wish.
但首先要记住,并不是每个地址都有数字,世界上大多数国家都不使用这种写地址的格式。至于地址字段,我相信您应该将其打开以按照用户希望的任何格式写入。