0

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!

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

won't work for "100." would recommend /^\d{1,10}\.?\d{0,2}$/
@David784 of course it won´t, that´s not a valid decimal number, else he wasn´t asking for numbers you´ve made regex for.
1

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">  

7 Comments

and at the starting i should include the script for additional methods right?
I'm sorry, I'm not sure what you mean. All you should have to change is to add the $.validator.methods statement somewhere in your $(document).ready(), above your $('#addForm').validate().
maxlength has been fixed here to 10 .So after that it doesnt show up decimal numbers.Should i remove the maxlength attribute?
can you provide a running snippet or on js fiddle ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.