GPiter
GPiter

Reputation: 799

Regex for validate a number with some criteria

I need to validate a number with those criterias :

  1. Can be float or integer
  2. Scale 4
  3. Precision 2

I tried like this :

pattern="/^[-+]?[0-9]\d*(\.\d+)?$/i",

Some examples :

  1. valid : 2; -1; 0.4; 0.12; 1928; 1827.78; -182.4
  2. invalid : 10000; 0.345; 89374.5;

Thx in advance.

Upvotes: 2

Views: 44

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You may use

'/^[-+]?(?:[1-9]\d{0,3}|0)(?:\.\d{1,2})?$/'

See the regex demo.

Details

  • ^ - start of string
  • [-+]? - either - or +
  • (?:[1-9]\d{0,3}|0) - a non-capturing group matching either
    • [1-9]\d{0,3} - a digit from 1 to 9 (non-zero) and any 0 to 3 digits
    • | - or
    • 0 - a zero
  • (?:\.\d{1,2})? - an optional non-capturing group matching 1 or 0 occurrences of
    • \. - a dot
    • \d{1,2} - 1 or 2 digits
  • $ - end of string.

Upvotes: 2

Related Questions