Jonah
Jonah

Reputation: 283

Limiting input field to one decimal point and two decimal places

I have an input field which is limited to 6 characters. How can I validate my input field so that a user can't put more than one decimal point (i.e. 19..12), plus it can only be to two decimal places as well (i.e. 19.123)?

This is my input field

<input type="text" name="amount" id="amount" maxlength="6" autocomplete="off"/><span class="paymentalert" style="color:red;"></span>

Here is my validation script.

$(function(){
$("#amount").keypress( function(e) {
    var chr = String.fromCharCode(e.which);
    if (".1234567890NOABC".indexOf(chr) < 0)
        return false;
});
});

$("#amount").blur(function() {
    var amount = parseFloat($(this).val());
    if (amount) {
        if (amount < 40 || amount > 200) {
            $("span.paymentalert").html("Your payment must be between £40 and £200");
        } else {
            $("span.paymentalert").html("");
        }
    } else {
        $("span.paymentalert").html("Your payment must be a number");
    }
});

Jonah

Upvotes: 0

Views: 13211

Answers (3)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382474

This should do :

var ok = /^\d*\.?\d{0,2}$/.test(input);

(if I correctly understood that you don't want more than 2 digits after the dot)

The code thus would be :

$("#amount").blur(function() {
    var input = $(this).val();
    if (/^\d*\.?\d{0,2}$/.test(input)) {
        var amount = parseFloat(input);
        if (amount < 40 || amount > 200) {
            $("span.paymentalert").html("Your payment must be between £40 and £200");
        } else {
            $("span.paymentalert").html("");
        }
    } else {
        $("span.paymentalert").html("Your payment must be a number");
    }
});

Upvotes: 3

talemyn
talemyn

Reputation: 7960

Assuming that:

  1. There MUST have 2 digits after a decimal point, and
  2. There must be at least 2 digits before the decimal point, but no more than 3 digits

The code you would use to match it would be:

var value = $(this).val;
value.match(/^\d{2,3}(\.\d{2})?$/i);

Upvotes: 2

Michael H&#228;rtl
Michael H&#228;rtl

Reputation: 8607

It would be much easier if you used the Masked Input Plugin for jQuery.

Upvotes: 1

Related Questions