Reputation: 42514
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
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
Reputation: 176956
use regular expression to validate your input field , regular rexpression is as below
^[0-9]+(?:\.[0-9]{1,3})?$
Upvotes: 0
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})?$/;
Upvotes: 2
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