Re: [thelist] JavaScript Validation for Pull-Down Menus and Radio Buttons — R E S O L V E D

Andrew Clover and-evolt at doxdesk.com
Fri Dec 10 03:23:16 CST 2004


Jono <ox4dboy at comcast.net> wrote:

> <SCRIPT LANGUAGE="JavaScript">

Time for nit-pick-fun! ;-)

<script type="text/javascript"> if you care about validation.

>     var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
>     if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }

You're trying to strip leading and trailing spaces, right?

This regexp doesn't quite hack it because it needs a \b word boundary at 
the end of the non-whitespace. However some non-whitespace characters do 
not generate a word boundary. For example in 'foo . ' the last \b is 
after the 'o' so the expression doesn't match.

Suggest \S instead, and simplify the redundant bits. Also I tend to 
avoid regexp literals as they can exhibit nasty cross-browser problems.

   var strip= new RegExp('^\\s*(.*\\S)?\\s*$')
   temp= temp.replace(strip, '$1');

>     if (temp == "") {

If this is all you're testing for, how about:

   var isOnlyWhitespace= new RegExp('^\\s*$');
   if (isOnlyWhitespace.test(temp)) {

> //this handles the radio buttons

(In practice, if one of the radios has 'checked' at the beginning it 
shouldn't be possible to unset them all.)

>     for (i=0;i<fieldobject.length;i++) {

for (var i= 0; is best. JavaScript's requirement that local variables be 
explicitly declared local is a real annoyance, especially when one 
function calls another in a loop and they both end up using a global 
'i'. Argh.

> onsubmit="if(isRequiredDoesNotEqual(this.commname, 'none', 'Community  
> Name') && isRequired(this.bldnumber,'Building Number') &&  

Careful with those ampersands. In HTML attributes they should be &amp;.

-- 
Andrew Clover
mailto:and at doxdesk.com
http://www.doxdesk.com/


More information about the thelist mailing list