mojodro
mojodro

Reputation: 65

jquery input field validation

I'm trying to validate user input data using jquery. Here is the code I use.

$('#ole').keypress(function(event) {
              if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
                event.preventDefault();
              }
            });

The code above allows only integers and a single dot. What I need is to allow only two integers after the dot.

How to achieve that ?

Upvotes: 0

Views: 894

Answers (2)

Richard de Wit
Richard de Wit

Reputation: 7452

Use a Regex expression and round the decimals:

$('#ole').on('blur', function()
{
    var val = $(this).val();

    if (val.match(/^\d+\.{0,1}\d+$/)) 
    {
        // Convert to int if needed
        val = parseInt(val);

        val = Math.round(val *100)/100; // Round to 2 decimals
        $(this).val(val);
    }
});​

Upvotes: 1

xkeshav
xkeshav

Reputation: 54016

TRY with this

HTML

<input id="ole" class="decimal">​

jQuery

$(document).on('change blur','.decimal',function() {
      var amt = parseFloat(this.value);
      if(isNaN(amt)) {
        $(this).val('');
      }
      else {
         $(this).val(amt.toFixed(2));
      }
    });

working DEMO

Upvotes: 3

Related Questions