Santosh
Santosh

Reputation: 2505

how to validate for money in jquery

how to validate for money in jquery where max amount i can enter is 9999.99 so my requirements are: 1.it should allow only digits and one dot 2.max length is 7(including dot) 3.before dot max length is 4 4.after dot max length is 2

currently my textbox allows only digits and one dot with the following code

$('#txtpaymentamnt, #txttenderamt').on("keypress", function (e) {
    alert(e.which);
    if (e.which != 8 && e.which != 0 && ((e.which < 48 || e.which > 57) && e.which != 46)) {
        e.preventDefault();
    }

Upvotes: 9

Views: 44249

Answers (4)

Moni
Moni

Reputation: 189

With jQuery validation plugin you can set your own rule using Jack's regular expression (which I haven't tested though) like this:

jQuery.validator.addMethod(
    "money",
    function(value, element) {
        var isValidMoney = /^\d{0,4}(\.\d{0,2})?$/.test(value);
        return this.optional(element) || isValidMoney;
    },
    "Insert "
);

Then you can set the rule within using the validate method:

$("#myForm").validate({
rules: {
    nameOfMyInputField: {
        money: true,
    }
}
});

Upvotes: 11

Nitin Varpe
Nitin Varpe

Reputation: 10694

As you said, if you are using MVC. MVC framework provides annotations which can be used to best effects. Even if there is no explicit data annotation for a decimal.

Following can be used for Two Decimal places

[RegularExpression(@"^\d+.\d{0,2}$")]

And for range you can use

[Range(0, 9999.99)]

So your model field becomes

[RegularExpression(@"^\d+.\d{0,2}$")]
[Range(0, 9999.99)]
public decimal Money{ get; set; }

Hope It Helps

Upvotes: 0

James Hibbard
James Hibbard

Reputation: 17755

You can do this with a regular expression: /^\d{0,4}(\.\d{0,2})?$/

EDIT:

Here's the requested fiddle

Upvotes: 19

pauix
pauix

Reputation: 45

If I were you, I'd use the isNumeric function in this answer to check if the input is a number and then check if the number is valid for your case.

To ve a "valid number" (according to your requirements), it has to:

  • Be between 0 and 9999.99 (maximum of 4 digits before the dot).

  • Have a maximum of 2 decimal digits. A good way to check that is to truncate the number after the nth digit (in your case, the second one) and compare it to the original value(two different values mean the second number has more decimal digits than the first). Use Math.round(number*100)/100 to truncate everything after the second decimal digit.

I hope this helps you with your problems.

Upvotes: 0

Related Questions