Thinking notes
思考笔记
2008-01-02
2006-12-29
JavaScript 验证数字 isNaN()
isNaN()
检测非数字值
如果x是特殊的非数字值NaN(或者能被转换为这样的值),返回值就是true。如果x是其它值,返回值是false。
isNaN()可以通过检测参数来判断值是否是NaN,该值表示一个非法的数字(如被0除后得到的结果)。这个
函数是必需的,因为把NaN与任何值(包括它自身)进行比较得到的结果都是false,所以要检测一个值是否
是NaN,不能使用==或者===运算符。
isNaN()通常用于检测方法parseFloat()和parseInt()的结果,以判断它们表示的是否是合法的数字。也可以用
isNaN()来检测算数错误,如用0作除数。
例子
|
2006-12-26
2006-12-13
IP Address Validation
We recently had a need on an intranet site to validate the format of IP addresses being entered. Remember that IP addresses must have 4 parts, separated by periods, and that each part must be in the range of 0 to 255. Also note that "000" for a part would be valid, as would "0".So, the first thing we do is make sure there are 4 groups of numbers (anywhere from 1 to 3 digits) separated by periods. Use a regular expression to do that. If the string passes that test, then split up the string into its 4 parts. The first part cannot be the number zero, so a check is done for that. None of the parts can be greater than 255, so just use a little loop to check the value of each part to make sure it is less than or equal to 255. If everything passes, return true, otherwise return false.
Note that we use "parseInt(parseFloat(...))" for checking. If we just used "parseInt" then if the user
entered "08" for the first part, the "parseInt" would return 0, which would fail even though the number
is valid.
function isValidIPAddress(ipaddr) {
var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
if (re.test(ipaddr)) {
var parts = ipaddr.split(".");
if (parseInt(parseFloat(parts[0])) == 0) {
return false;
}
for (var i=0; i255) {
return false;
}
}
return true;
} else {
return false;
}
}
Note that we use "parseInt(parseFloat(...))" for checking. If we just used "parseInt" then if the user
entered "08" for the first part, the "parseInt" would return 0, which would fail even though the number
is valid.
Subscribe to:
Posts (Atom)