Simon
Simon

Reputation: 1333

Regex decimal values between 0 and 1 up to 4 decimal places

I am writing a C# web application and verify data in a textbox using this regular expression that only accepts positive decimal values between 0 and 1:

^(0(\.\d+)?|1(\.0+)?)$

I would to adapt like the regex to restrict entries to 4 decimal places of precision.

Allowed

0
0.1
0.12
0.123
0.1234
1

Not allowed

-0.1
-1
1.1
2

I have found the following regex that only allows up to 4 decimal places, but I am unsure on how to combine the two.

^(?!0\d|$)\d*(\.\d{1,4})?$

Any help is greatly appreciated, thanks.

Upvotes: 6

Views: 3030

Answers (2)

NIKITA KHETADE
NIKITA KHETADE

Reputation: 1

This can be used as the validation function that allows four digit decimal place in terms of regular expession (RegExp).

function fourdecimalplace(e) {
    var val = this.value;
    var re = /^([0-9]+[\.]?[0-9]?[0-9]?[0-9]?[0-9]?|[0-9]+)$/g;
    var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?[0-9]?[0-9]?|[0-9]+)/g;

    if (re.test(val)) {
        //do something here

    } else {
        val = re1.exec(val);
        if (val) {
            this.value = val[0];
        } else {
            this.value = "";
        }
    }

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You need to set replace the + quantifier with the limiting {1,4}:

^(0(\.[0-9]{1,4})?|1(\.0{1,4})?)$
           ^^^^^        ^^^^^ 

See the regex demo

Details:

  • ^ - start of string
  • ( - Outer group start
    • 0 - a zero
    • (\.[0-9]{1,4})? - an optional sequence of a . followed with 1 to 4 digits
    • | - or
    • 1 - a 1
    • (\.0{1,4})?) - an optional sequence of . followed with 1 to 4 zeros
  • $ - end of string.

Upvotes: 5

Related Questions