javascript 检查字符串是否只包含数字,否则显示消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10380937/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:40:28  来源:igfitidea点击:

check if string contains only numbers, else show message

javascriptvalidation

提问by Darren Burgess

I have a simple form, which performs a calculation when a digit is pressed, however this should only happen when numbers are typed, if a letter is added i would like for a notification to appear. Is there a simple function to do this?

我有一个简单的表格,它在按下数字时执行计算,但是这只应该在输入数字时发生,如果添加了一个字母,我希望出现通知。有没有一个简单的功能来做到这一点?

Form

形式

    <input onKeyPress="return onlyNumbers()" onKeyUp="calc()" id="value1" type="text" name="value1">
    <select onChange="calc()" id="manipulator" name="manipulator">
        <option value="commission">Commission</option>
        <option value="cost">Return</option>
    </select>
</form>

calc function

计算函数

function calc(){
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    val1 = document.getElementById("value1").value;
    mani = document.getElementById("manipulator").value;

    if (val1 != ""){
        document.getElementById("resp").innerHTML="Calculating...";
        queryPath = "comCalcServ.php?value1="+val1+"&manipulator="+mani;

        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                document.getElementById("resp").innerHTML=xmlhttp.responseText;
            }
        }

        xmlhttp.open("GET",queryPath);
        xmlhttp.send();
    }
}

I am currently looking at the isNaN function but not familiar with the JS syntax so unsure where to use it.

我目前正在查看 isNaN 函数,但不熟悉 JS 语法,因此不确定在哪里使用它。

回答by Sudhir Bastakoti

Do you mean:

你的意思是:


//add inside your calc function
val1 = document.getElementById("value1").value;
if(/^\d+$/.test(val1)) {
 //proceed with rest of code
}
else {
 alert("Invalid");
 return false;
}

回答by shreedhar bhat

Try this simple one

试试这个简单的

if(val1.match(/^\d+$/)) {
    // your code
} 

回答by kaustubh

the above code did not work in my case . so i made few changes . i just changed regex to /^[0-9]*$/.test(val1)and it worked.

上面的代码在我的情况下不起作用。所以我做了一些改变。我只是将正则表达式更改为/^[0-9]*$/.test(val1),它起作用了。