JS How to verify that the user input can only be a number?

Source: Internet
Author: User

Method One
If you determine whether the input is a number, if it is not a number popup a hint: The simple code is as follows:
<body>
<input type= "text" id= "INP" ></table>
</body>
<script>
var oinp = document.getElementById (' InP ');
Oinp.onblur=function () {
if (IsNaN (number (Oinp.value))) {//when the input is not a digit, the value returned is Nan, and then judged by IsNaN.
Alert (' Not a number! ‘)
}
}
</script>




Method Two:
<script language= "JavaScript" >
function Checkmyform ()
{
var txt = myform.mytext.value;
if (CheckNumber (TXT))
{
Alert ("Only allow numbers! ");
return false;
}
return true;
}
function CheckNumber (String)
{
var Letters = "1234567890";
var i;
var C;
for (i = 0; i < string.length; i + +)
{
c = String.charat (i);
if (Letters.indexof (c) ==-1)
{
return true;
}
}
return false;
}
</script>
<body>
<form name= "MyForm" onsubmit= "return Checkmyform ()" >
<input type= "text" name= "MyText" >
<input type= "Submit" Name= "Mysubmit" >
</form>
</body>

method Three: Regular expressions

The most complete and accurate method: (Regular expression)

1)

"^\\d+$"//nonnegative integer (positive integer + 0)
"^[0-9]*[1-9][0-9]*$"//Positive integer
"^ ((-\\d+) | (0+)) $ "//non-positive integer (negative integer + 0)
"^-[0-9]*[1-9][0-9]*$"//Negative integer
"^-?\\d+$"//Integer
"^\\d+ ("//non-negative floating-point number (positive floating point + 0)
^ ([0-9]+\\]. [0-9]*[1-9][0-9]*) | ([0-9]*[1-9][0-9]*\\. [0-9]+) | ([0-9]*[1-9][0-9]*)) $ "//positive floating-point number
"^ ((-\\d+ ("///non-positive floating-point number (negative float + 0)
^ (-([0-9]+\\]. [0-9]*[1-9][0-9]*) | ([0-9]*[1-9][0-9]*\\. [0-9]+) | ([0-9]*[1-9][0-9]*))) $ "//negative floating-point number
^ (-?\\d+) ("//floating-point
2)

var r =/^\+? [1-9]  [0-9]*$/; Positive integers
R.test (str);











JS How to verify that the user input can only be a number?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.