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,]*$');
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 stringYour 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));
});