1154 Part V . Putting JavaScript to Work (Web servers)
1154 Part V . Putting JavaScript to Work In the ifcondition, the ASCII value of each character is compared against the range of 0 through 9. This method is safer than comparing numeric values of the single characters because one of the characters can be nonnumeric. (You can encounter all kinds of other problems trying to convert that character to a number for numeric comparison.) The ASCII value, on the other hand, is neutral about the meaning of a character: If the ASCII value is less than 0 or greater than 9, the character is not valid for a genuine positive integer. The function bounces the call with a false reply. On the other hand, if the for loop completes its traversal of all characters in the value without a hitch, the function returns true. You may wonder why this validation function doesn t use the parseInt()global function (Chapter 42). That function returns NaNonly if the first character of the input string is not a number. But because parseInt()and parseFloat() peel off any initial numeric values from a string, neither returns NaN if the input string is, for example, 35a. isInteger() The next possibility includes the entry of a negative integer value. Listing 43-4 shows that you must add an extra check for a leading negation sign. Listing 43-4: Checking for Leading Minus Sign // general purpose function to see if a suspected numeric input // is a positive or negative integer function isInteger(inputVal) { inputStr = inputVal.toString() for (var i = 0; i < inputStr.length; i++) { var oneChar = inputStr.charAt(i) if (i == 0 && oneChar == - ) { continue } if (oneChar < 0 || oneChar > 9 ) { return false } } return true } When a script can accept a negative integer, the filter must enable the leading minus sign to pass unscathed. You cannot just add the minus sign to the if condition of Listing 43-3 because you can accept that symbol only when it appears in the first position of the value anywhere else makes the value an invalid number. To handle the possibility of a leading minus sign, you add another if statement whose condition looks for a special combination: the first character of the string (as indexed by the loop-counting variable) and the minus character. If both of these conditions are met, execution immediately loops back around to the update expression of the forloop (because of the continue statement) rather than carrying out the second if statement, which would obviously fail. By putting the i == 0 comparison operation at the front of the condition, you ensure the entire condition short circuits to false for all subsequent iterations through the loop.
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.