Home >Web Front-end >JS Tutorial >Summary of methods to use JS to determine whether a string contains numbers and special characters
Foreword
This article mainly introduces the method of using JS to determine whether a string contains numbers and special characters. There are several different methods in the article, including ordinary JS verification method, regular expression method, and also judging whether it is a float. Points js function, at the end we will briefly introduce the usage and examples of isNAN function, let’s learn together.
1. Regular expression method to determine whether it is a number, including determining positive integer:
function checkRate(input) { var re = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字,//若判断正整数,则后边是:/^[1-9]+[0-9]*]*$/ if (!re.test(input.rate.value)) { alert("请输入数字(例:0.02)"); input.rate.focus(); return false; } }
2. Ordinary JS function method:
function BASEisNotNum(theNum) { if (BASEtrim(theNum)=="") return true; for(var i=0;i<theNum.length;i++){ oneNum=theNum.substring(i,i+1); if (oneNum<"0" || oneNum>"9") return true; } return false; }
3. Determine whether it is a positive number, that is Positive integer:
function BASEisNotInt(theInt) { theInt=BASEtrim(theInt); if ((theInt.length>1 && theInt.substring(0,1)=="0") || BASEisNotNum(theInt)){ return true; } return false; }
4. Determine whether the string is composed of numbers and other symbols, such as "-":
function ismonth(str) { for(ilen=0;ilen<str.length;ilen++) { if(str.charAt(ilen) < '0' || str.charAt(ilen) > '9' ) { if((str.charAt(ilen)!='-')) return false; } } return true; }
5. Determine whether it is a floating point number:
function BASEisNotFloat(theFloat) { len=theFloat.length; dotNum=0; if (len==0) return true; for(var i=0;i<len;i++){ oneNum=theFloat.substring(i,i+1); if (oneNum==".") dotNum++; if ( ((oneNum<"0" || oneNum>"9") && oneNum!=".") || dotNum>1) return true; } if (len>1 && theFloat.substring(0,1)=="0"){ if (theFloat.substring(1,2)!=".") return true; } return false;
About the isNaN function of javascript: Usage rules: isNaN(expression:Object): Boolean. Computes a parameter and returns true if the value is NaN (not a number). This function can be used to check whether a mathematical expression evaluates successfully to a number.
Availability: Flash Player 5; ActionScript 1.0; Parameter expression: Object - Boolean value, variable or other expression to be evaluated. Returns Boolean - Boolean value.
is often used like this in submission forms:
<script> if(isNaN(document.login.imgcode.value)){ alert('验证码不是数字!') document.login.imgcode.focus(); return false; } </script>