In js, we can use regular expressions to check whether the variable is a number. In addition to regular expressions, we can also use the isNaN function to check for non-numeric values. In this way, we can also obtain numbers, the following is an example.
Use isNaN () to determine numbers
The isNaN () function is used to check whether the parameter is a non-numeric value.
Note:
The isNaN () function can be used to determine whether the parameter is NaN. This value indicates an invalid number (for example, the result obtained after being divided by 0 ).
If the result of comparing NaN with any value (including its own) is false, you cannot use the = OR = Operator to determine whether a value is NaN. Because of this, the isNaN () function is required.
Test:
The Code is as follows: |
Copy code |
Document. write (isNaN (123); // false Document. write (isNaN (-1.23); // false Document. write (isNaN (5-2); // false Document. write (isNaN (0); // false Document. write (isNaN ("Hello"); // true Document. write (isNaN ("2005/12/12"); // true Document. write (isNaN ("6/2"); // true Document. write (isNaN ("3"); // false
|
Example
Calculate the parameter. If the value is NaN (not a number), true is returned. This function can be used to check whether a mathematical expression is successfully calculated as a number.
The Code is as follows: |
Copy code |
If (isNaN (document. login. imgcode. value )){ Alert ('verification code must be a number! ') Document. login. imgcode. focus (); Return false; } If (! IsNum (document. getElementById ("prjSum"). value )){ Alert ("cost can only be a number "); Document. getElementById ("prjSum"). focus (); Return false;
} |
Use regular expressions to check numbers
A good code that uses regular expressions to check whether the entered characters are numbers is not uncommon.
The Code is as follows: |
Copy code |
<! Doctype html public "-// W3C // dtd html 4.01 // EN" "http://www.w3.org/TR/html4/strict.dtd"> <Html> <Head> <Meta http-equiv = "Content-Type" content = "text/html; charset = GB2312"/> <Title> Untitled Document </title> </Head> <Body> <Input type = "text" id = "myInput" value = ""/> <Input type = "button" value = "OK" id = "myButton"/> </Body> </Html> <Script language = "JavaScript" type = "text/javascript"> Function $ (obj ){ Return document. getElementByIdx (obj ); } Function checkIsInteger (str) { // If it is null, it passes verification. If (str = "") Return true; If (/^ (-?) (D +) $/. test (str )) Return true; Else Return false; } String. prototype. trim = function () { Return this. replace (/(^ [s] *) | ([s] * $)/g ,""); } $ ("MyButton"). onclick = function (){
If (checkIsInteger ($ ("myInput"). value. trim ())){ Alert ("successful "); } Else { Alert ("only numbers "); } } </Script> |