Javascript - 验证,仅限数字 [英] Javascript - validation, numbers only
问题描述
我正在尝试让我的登录表单只验证是否只输入了数字。如果输入只是数字,我可以工作,但是当我在数字后键入任何字符时,它仍然会验证等.12akf将起作用。凌晨1点就行了。我怎么能超过这个?
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?
登录的一部分
<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)")
}
}
推荐答案
与 / ^ \d + $ /
匹配。 $
表示行尾,因此在初始数字运行后的任何非数字字符都会导致匹配失败。
Match against /^\d+$/
. $
means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.
修改:
RobG明智地建议更简洁 /\D/.test(z )
。此操作测试您想要的反转。如果输入任何非数字字符,则返回 true
。
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 any non-numeric characters.
简单省略否定!
并使用 if(/\D/.test(z))
。
这篇关于Javascript - 验证,仅限数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!