Javascript - 验证,仅限数字 [英] Javascript - validation, numbers only

查看:20
本文介绍了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 - 验证,仅限数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆