Home > Mobile >  Javascript Regular Expression for 3 digit and 1 decimal input
Javascript Regular Expression for 3 digit and 1 decimal input

Time:05-13

I have an HTML tag with input type: number. I would like to set a pattern that allows only specific format input: 3 digits and 1 decimal value, for example:

123.1 -> is valid
123.12 -> not valid 
123 -> not valid

Only the first format is valid, everything else is not valid. Also the dot '.' should be interchangeable with the coma ','.

123,1 -> is also valid

CodePudding user response:

You could use

^\d{3}[\.,]\d$
Regex explanation
^ start of string
\d{3} exactly 3 digits
[\.,] either a decimal point or comma
\d a single digit
$ end of the string

CodePudding user response:

You can use this regex:

/^\d{3}[,\.]{1}\d/g

CodePudding user response:

I think this could suit you. Basically, I make sure that there is nothing before the first 3 digits. Then, I check that the number is followed by either a dot or a comma plus a single digit with nothing else after it.

^\d{3}(\.\d$|,\d$)

https://regex101.com/r/7t7T30/6

  • Related