Hi all,

I find the default javascript validators for integer, double, and decimal 
SQLFORM fields to be a little annoying. Consider the following surprising 
behaviors:

- You can't navigate within the textbox using the keyboard. Pressing left, 
right, home, or end all result in the cursor jumping back to the end of the 
input
- You can't select text with ctrl-a or ctrl-shift-left/right
- If the user accidentally flubs the input (e.g. 2.u1828 instead of 
2.71828), the offending character is silently removed and an incorrect value 
may be submitted without warning.

I think a better alternative is to flag to the user that the input is wrong 
rather than trying to correct it for them -- e.g. by changing the input 
background color. The following is a sample implementation that does this:

-- in file web2py_ajax.html, replace the lines 
"jQuery('input.integer').live..." and 
"jQuery('input.double,input.decimal').live..." with:

  jQuery('input.integer').live('keydown keyup', function(){
     if (! this.value.match(/^[+-]?[0-9]*$/)) {
          jQuery(this).addClass("w2p_inputerror");
     }
     else {
          jQuery(this).removeClass("w2p_inputerror");
     }
  });

  jQuery('input.double,input.decimal').live('keydown keyup', function(){
     if (! this.value.match(/^[+-]?[0-9]*\.?[0-9]*$/)) {
          jQuery(this).addClass("w2p_inputerror");
     }
     else {
          jQuery(this).removeClass("w2p_inputerror");
     }
  });

-- in file base.css, add the following style:

     input.w2p_inputerror {
          background: #FF8;
     }


A few notes:

1. The regexes used to validate numbers are "intentionally" naive. For 
example. the double validator accepts "+", "-", "+.", and "-.", which are of 
couse not valid numbers. However, suppose the user enters a value between -1 
and 0. They are likely to start by typing "-.", and I don't think it's 
polite to flash the textbox at them when they are about to enter a valid 
number.

2. The double validator does not permit scientific notation - e.g. "1e6" for 
1 million. Such notation is probably of limited use for most people, the old 
validator rejected such values anyway, and I didn't feel like implementing 
it :-)

3. The jquery events listen to both keyup and keydown. keyup is necessary 
because the input.value has not yet been updated when keydown is fired. But 
listening to keydown is useful if the user holds down the backspace key - 
the background color will be reset as soon as the last offending character 
has been deleted, rather than waiting for the user to release the backspace 
key.

4. I used the class name "w2p_inputerror" in an attept to namespace this 
somewhat web2py-specific class.


I hope some people find this to be useful. If other people have been annoyed 
by the current default, perhaps we could open discussion to make this the 
new default in web2py?

Cheers,
Kevin

Reply via email to