coure2011
coure2011

Reputation: 42514

allow input with decimal places upto 3

I want to allow only integers and floats (upto 3 decimal places) in a text box, how can I achieve this using javascript?

Valid values are

1234
12.3
12.314
1.11
0.4

Not valid

1.23456
abcd or any other character 

Upvotes: 0

Views: 3870

Answers (4)

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this:

var reg=/^[\d]+(?:\.\d{1,3})?$/;
str=10.2305;
str1=123;
alert(reg.test(str));
alert(reg.test(str1));

Check Fiddle http://jsfiddle.net/8mURL/1

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176956

use regular expression to validate your input field , regular rexpression is as below

^[0-9]+(?:\.[0-9]{1,3})?$

Upvotes: 0

epascarello
epascarello

Reputation: 207557

Based on the comment that you need to also match ".1" you need to add a conditional with the first part of the regular expression.

var re = /^(\d+)?(?:\.\d{1,3})?$/;

Rough test suite - jSFiddle

Upvotes: 2

Anthony Grist
Anthony Grist

Reputation: 38345

You can use a regular expression to do this:

/^\d+(?:\.\d{1,3})?$/

That's the start of the string (^), one or more digits (\d+), optionally followed by a . and between 1 and 3 digits ((?:\.\d{1,3})), then the end of the string ($).

To compare it to the value of an input, you'd do something like this:

var re = /^\d+(?:\.\d{1,3})?$/;
var testValue = document.getElementById('id-of-input').value;
if(re.test(testValue)) {
    // matches - input is valid
}
else {
    // doesn't match - input is invalid
}

Take a look at this jsFiddle demo.

Upvotes: 1

Related Questions