Dilip chabaria
Dilip chabaria

Reputation: 5

Validating Decimal numbers using validation plugin

I have an input element in my form in which the user inputs price for a specific product. To do so he can either put an amount with decimal numbers or he can simply put a price without the decimal numbers.

<input type="text" id="product_price" name="product_price" maxlength="10" step="0.01" placeholder="Enter price">
$('#addForm').validate({
    rules:{
        product_name: {
            required: true,
        },
        product_price: {
            required: true,
            number: true
        }
    }
})

This is what I did however I don't get what I wanted to achieve. I am trying to make it so that a user can put a number of length 10 up to two decimals. For example, if he enters 1111111111 or 1111111111.11 These both should be valid. What should I do and what be the code?

Thanks!

Upvotes: 0

Views: 769

Answers (2)

PDKnight
PDKnight

Reputation: 722

Use regex. In JavaScript,

if (/^\d{1,10}(\.\d{2})?$/.test(product_price.value))
    // do stuff

This regex should match 1, 46871325, 18671.68 but not 46812547.178687.

Btw, you don't need maxlength and step attributes, just remove them :)

Fiddle

Upvotes: 2

David784
David784

Reputation: 7464

Not sure if it's just me, but I couldn't get the step to work reliably. But it appears that validation will allow you to override the method for number (or any of its other types). So here's what I would probably do:

$.validator.methods.number = function(value,e) {
    return this.optional(e) || /^\d+\.?\d{0,2}$/.test(value)
};

The regex will verify that at least one number has been entered, optionally followed by a decimal point and up to two additional numbers.

And then remove the step:

<input type="text" id="product_price" name="product_price" maxlength="10" placeholder="Enter price">  

Upvotes: 1

Related Questions