0

I want Regex for Javascript for below validation:

Textbox should allow only 2 digit numbers and 3 digit numbers as comma separated. Ex: 12,123,56,567,789,11

Satheesh
  • 11
  • 2
  • 1
    Welcome to StackOverflow. We’d love to help you. To improve your chances of getting an answer, here are some tips: stackoverflow.com/help/how-to-ask – Dumi Dec 17 '18 at 10:59

5 Answers5

1

Hey welcome to Stackoverflow,

try this one

  • ([0-9]{1,3},)* - last two or three digit should be without comma

  • (\d{1,3},)*$ - last two or three digit should have comma

  • (\d{2,3}),? - captures both case - wether last two digit have comma or not

You can test regular expressions online in this website - make sure the javascript is selected

Mansour
  • 204
  • 4
  • 12
0

Try this regular expression instead /([0-9]{2,3}),?/gi

This will capture any 2 or 3 digit numbers, without the optional , separator.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
V. Dimitrov
  • 162
  • 1
  • 12
0

Check this Regex too.

[0-9]{2,3}[,]{0,1}

https://regexr.com/452l2

Prashant Deshmukh.....
  • 2,244
  • 1
  • 9
  • 11
0
^               # beginning of line
  \d{2,3}       # 2 or 3 digits
  (?:           # start non capture group
    ,           # a comma
    \d{2,3}     # 2 or 3 digits
  )*            # end group may appear 0 or more times
$               # end of line

If you don't want numbers that start with 0 like 025

^               # beginning of line
  [1-9]         # digit fomr 1 to 9
  \d            # 1 digit
  \d?           # 1 optional digit
  (?:           # start non capture group
    ,           # a comma
    [1-9]       # digit fomr 1 to 9
    \d          # 1 digit
    \d?         # 1 optional digit
  )*            # end group may appear 0 or more times
$               # end of line

DEMO

Toto
  • 89,455
  • 62
  • 89
  • 125
0

This regex will match all your cases: ^(?:\d{2,3},)+(\d{2,3}),?$|^\d{2,3}$

https://regex101.com/r/CdYVi9/2

Sample JS:

const isValid = str => /^(?:\d{2,3},)+(\d{2,3}),?$|^\d{2,3}$/.test(str);
Grafluxe
  • 483
  • 4
  • 11