views:

33

answers:

1

I am using the jQuery validation plugin and I would like to validate a floating point number and format it to a specified number of decimal places.

I am using

element.value = parseFloat(value).toFixed(param);

to format the floating point value if it is indeed a valid floating point value, I just only want to do this on blur, not on keyup as this yields odd results. I do however want to validate the input on keyup.

I guess what I am looking for is basically

if( validation was triggered by blur )
{
    element.value = parseFloat(value).toFixed(param);
}
A: 

The jQuery validation plugin does not allow you to mix rules like that (I might be wrong, there may be an option to do that, but this problem is easy enough to solve without it anyway.)

First, for the keyup validation:

$('#float').keyup(function(){
  if(!/[-+]?[0-9]*\.?[0-9]+/.test(this.value)){
    // Do something about the error
  }
});

You might want to rollback the edit or display an error message, whatever. Now, on blur

$('#float').blur(function(){
  var input = this.value;

  if(/[-+]?[0-9]*\.?[0-9]+/.test(input)){
    this.value = parseFloat(input).toFixed(param);
  }
});

There, simple.

NB: Regex from http://www.regular-expressions.info/floatingpoint.html

Yi Jiang