[thelist] [JS] Truly checking for empty fields

Tom Dell'Aringa pixelmech at yahoo.com
Fri Apr 9 09:49:33 CDT 2004


Along the same lines - I've always wondered about this one. When you
require a field to not be empty, often you see validations do the
following:

if(myField.value == ""){
  return false
}

This is fine for a tab or if the field is truly empty, but if I
simply enter a space I can bypass this validation. If you aren't then
validating the *type* of data afterwards, this can sneak through your
validation.

We have this function available which seems to work:

function requiredField(field) {
    var nonblanks = 0;
    var thisChar;
    
    for (i = 0; i < field.value.length; i++) {
        thisChar = field.value.charCodeAt(i);
        
        // 32 is a blank; 9 is a tab
        if (thisChar != 32 && thisChar != 9) 
            nonblanks += 1;
    }
    
    if (nonblanks == 0) {
        return false;
    }
    return true;
}

I'm not sure how reliable checking for the characer numbers 32 and 9
is. (Note: No need to support anything prior to NS6 or IE5). But it
seems to work. And again, I'm wondering if a regex is not a better
solution here.

Comments?

Tom

=====
http://www.Pixelmech.com/ - read my latest blog posting!
http://www.DMXzone.com/ - JavaScript Author
http://SparklesParties.com - Princess parties for little girls!
http://www.thywordistruth.net/ - Eternal Life

"Well, my name's Dewey Oxburger. My friends call me Ox. I dont know if you've noticed, but I got a slight weight problem."





More information about the thelist mailing list