Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
like image 702
Santosh Avatar asked Jan 09 '14 10:01

Santosh


People also ask

How do you validate a value in Javascript?

Approach: We have used isNaN() function for validation of the textfield for numeric value only. Text-field data is passed in the function and if passed data is number then isNan() returns true and if data is not number or combination of both number and alphabets then it returns false.


2 Answers

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

EDIT:

Here's the requested fiddle

like image 159
James Hibbard Avatar answered Oct 24 '22 12:10

James Hibbard


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,
    }
}
});
like image 11
Moni Avatar answered Oct 24 '22 11:10

Moni