Javascript - validation, numbers only(Javascript - 验证,仅限数字)
问题描述
我试图让我的登录表单仅验证是否只输入了数字.如果输入只是数字,我可以工作,但是当我在数字后键入任何字符时,它仍然会验证等.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)
.此操作测试您想要的相反.如果输入有 any 个非数字字符,则返回 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))
.
Simply omit the negating !
and use if(/D/.test(z))
.
这篇关于Javascript - 验证,仅限数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Javascript - 验证,仅限数字


基础教程推荐
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01