Tanwer
Tanwer

Reputation: 1583

regex to accept number in fomat 00.00

In my Angular App I am trying to set validation on input field such as

it should accept only 2 digit number or floating point number with 2 digit after point and before point too

Example

Accepted value

3, 33, 33.3, 33.33

Max value can be 99.99

Not accepting

333 33.333 3.333 333.33

Currently I am using

pattern="[+]?((\d{1,2})+(?:[\.][0-9]{0,2})?|\.[0-9]{0,2})$"

it validate 2 digit after point but failed to validate two digit before point as it accept 333.33 (which is wrong)

I also tried

pattern="[+]?(([0-9])+(?:[\.][0-9]{0,2})?|\.[0-9]{0,2})$"

But same thing happen , it does not validate two digit before point

Upvotes: 0

Views: 820

Answers (2)

The fourth bird
The fourth bird

Reputation: 163287

This pattern (\d{1,2})+ will match 1 - 2 digits and will repeat that one or more times.

A pattern like \.[0-9]{0,2} will also match just a single dot because the digits will match 0 - 2 times.

You could use an anchor to assert the start ^ and the end $ of the string. Match 1 or 2 digits with an optional part that matches a dot and 1 or 2 digits:

^\d{1,2}(?:\.\d{1,2})?$

Regex demo

Explanation

  • ^ Assert the start of the string
  • \d{1,2} Match a digit 1 or 2 times
  • (?: Non capturing group
    • \.\d{1,2} Match a dot literally and 1 or 2 digits
  • )? Close non capturing group and make it optional
  • $ Assert the end of the string

If you want to match an optional plus at the beginning, the start of the regex could be^\+?

let pattern = /^\d{1,2}(?:\.\d{1,2})?$/;
let strs = [
  "99",
  "3",
  "33",
  "33.3",
  "33.33",
  "333",
  "33.333",
  "3.333",
  "333.33"
];

strs.forEach((s) => {
  console.log(s + " ==> " + pattern.test(s));
});

Upvotes: 4

RobG
RobG

Reputation: 147383

It seems to me the regular expression can be simplified. Do you really want an optional leading "+"? I've left it out as your examples don't include it, put it back in if you want.

function testValue(){
  // Optional leading +
  // var re = /^\+?\d{1,2}(\.\d{1,2})?$/;
  // No leading +
  var re = /^\d{1,2}(\.\d{1,2})?$/;
  console.log(re.test(this.value));
}


window.onload = function(){
  document.querySelector('input').addEventListener('input',testValue,false);
}
Enter number: <input>

Upvotes: 2

Related Questions