How implement regex for a textfield to allow one comma one dot at a time in Extjs

463 views Asked by At

I am working on a textfield to make it allow only numbers with max one comma and one dot(max) at any occurrence. It can accept value like "9.8,8.6". It should not allow two or more dots or commas at a time.

I have tried below code but its not working.

this.regex = new RegExp('[\d,]\.?[\d,]*$');
1

There are 1 answers

11
The fourth bird On BEST ANSWER

Your current pattern has a lot of optional parts. It would also allow for example a single comma.

If the max is only 1 comma and 1 dot per number before or after the comma, you could make it optional:

^(?:\d+(?:\.\d+)?|\.\d+)(?:,(?:\d+(?:\.\d+)?|\.\d+))*$
  • ^ Start of string
  • \d+ Match 1+ digits
  • (?:\.\d+)* Match 0+ times a dot and 1+ digits
  • (?: Non capturing group
    • ,\d+(?:\.\d+) match comma, 1+ digits and optionally a dot and 1+ digits
  • )? Close group and make it optional
  • $ End of string

Regex demo

Your code could look like (Note to double escape the backslashes)

this.regex = new RegExp('^(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:,(?:\\d+(?:\\.\\d+)?|\\.\\d+))*$');

let regex = new RegExp('^(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:,(?:\\d+(?:\\.\\d+)?|\\.\\d+))*$');

[
  "9.8,8.6",
  "9.8",
  "8.2,9",
  "5,9",
  "9.8,8.6,1.1",
  "1,8.6",
  "9.8,8.6,1.1",
  "8,8,8",
  "9.8,8,8",
  "1,1",
  "1,1,.1,1",
].forEach(s => {
  console.log(s + " ==> " + regex.test(s));
});