Forum Moderators: open

Message Too Old, No Replies

Spell it out please, what does this function do (say)

         

evolistic

8:18 am on May 29, 2007 (gmt 0)

10+ Year Member



I'm new to JavaScripting and am looking at code samples in various places. Now I'm wondering if someone can help explain to me what the code below actually does. I realize that it checks for the characters listed in the illegalChars variable. But the part I would like to have "read out loud" is the 2 first lines of the function.

Hope someone can find the time to help.

Thanks in advance

function checkForChars(fieldValue, fieldName){
var illegalChars = "1234567890";

for (var i = 0; i < fieldValue.length; i++) {
if (illegalChars.indexOf(fieldValue.charAt(i))!= -1) {
alert ("The filename contains illegal characters.);
return false;
}
}
}

phranque

11:00 am on May 29, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



function checkForChars(fieldValue, fieldName){
var illegalChars = "1234567890";

for (var i = 0; i < fieldValue.length; i++) {
if (illegalChars.indexOf(fieldValue.charAt(i))!= -1) {
alert ("The filename contains illegal characters.);
return false;
}
}
}

this line initializes a string that contains all possible numeric digits:
var illegalChars = "1234567890";

this line iterates on a loop where i goes from 0 to n where n = (number of characters in fieldValue) - 1:
for (var i = 0; i < fieldValue.length; i++) {

this line checks if the ith (charAt(i)) character in fieldValue (fieldValue.charAt(i)) exists in illegalChars (if it exists indexOf returns a positive number indexing to the first occurence, otherwise -1 means it doesn't exist):
if (illegalChars.indexOf(fieldValue.charAt(i))!= -1) {

if checkForChars returns true you have all non-numeric digits in fieldValue.

Dabrowski

5:17 pm on May 29, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This function could be abbreviated to:

function checkForChars(fieldValue){
return fieldValue.match( /\d/);
}

That's called a regular expresion, the \d means any numerical character. It'll return null, or false, if there is no numeric characters.

I've also removed the fieldName argument, as it didn't seem to be used.