regexextjsextjs6.5

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


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

Solution

  • 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+))*$
    

    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));
    });