简体   繁体   中英

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 

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

使用正则表达式验证您的输入字段,正则表达式如下

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM