0

I am trying to make an HTML input to only be able to receive float numbers like: x.123 x,123 x.123456 x,123456

Where x can have one or 2 digits: x or xx.

Basically I would like to know how to make a pattern that only accepts those kind of numbers.

Reading around the WEB I found two patterns that should've matched my needs, but they do not work.

^[+-]?([0-9]*[.])?[0-9]+$ ^(?=.)(\d{1,2}(,\d{3,6})*)?(\.\d+)?$

These were found, I don't understand how this works.

Googling Regex I found a lot of tools that work for,on or with (I don't have any idea) JavaScript, PHP, RUBY, PCRE.

I don't understand what coding language they use or how. And after digging into it more I found myself even more lost and having more questions.

Is there any reverse tool that actually makes the regex ?

I found this http://buildregex.com/ but I don't know how it works... This is me trying to make my pattern...

/(?:(?:(?:(?:(?:(?:)|(?:(?:22\.123))|(?:(?:2\.123))|(?:(?:22\.123))|(?:)|(?:)|(?:))))))/

EDIT:

This is is the input:

<input id="text-input" type="text" inputmode="numeric" pattern="/^[\d]{1,2}[.,][\d]{3,6}$/"
                                    oninvalid="this.setCustomValidity('Please enter a number with 3-6 decimals')"
                                    onchange="try{setCustomValidity('')}catch(e){}"
                                    oninput="setCustomValidity(' ')"
>


bleah1
  • 451
  • 2
  • 13
  • `x.y` or `x,y` where x is 1 to 2 digits and y is 3 to 6 digits ? – Cid Jun 07 '19 at 12:09
  • Yes, That's correct ! – bleah1 Jun 07 '19 at 12:11
  • 1
    HTML5 patterns cannot have regex delimiters, `/` are parsed as parts of the regex *pattern*. Also, they are always anchored, they must match the entire string, hence no need using `^` and `$`. Use `pattern="\d{1,2}[.,]\d+"` – Wiktor Stribiżew Jun 07 '19 at 12:21
  • @WiktorStribiżew Thank you ! That's why it wasn't working. Taking `/^[\d]{1,2}[.,][\d]{3,6}$/` from @Cid and removing the delimiters `/` made it work. – bleah1 Jun 07 '19 at 12:25
  • 1
    Use `pattern="\d{1,2}[.,]\d{3,6}"` then, no need to wrap `\d`s with brackets, and again, the anchors are added behind the scenes, `^(?:pattern)$` – Wiktor Stribiżew Jun 07 '19 at 12:26

3 Answers3

2

You can use pattern="^\d{1,2}[.,]\d{3,6}$"

^\d{1,2} starting with 1 to 2 digit(s)

[.,] followed by either a comma, either a dot

\d{3,6}$ ending by 3 to 6 digits

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
Cid
  • 13,273
  • 4
  • 22
  • 42
1

There're no needs for delimiters and anchors, use:

pattern="\d{1,2}[.,]\d{3,6}"
Toto
  • 83,193
  • 59
  • 77
  • 109
1
^\d{1,2}[\.]\d{3,6}$ ,

^d{1,2} means: max 2 digit start with.

[\.] means : having . in middle.

d{3,6} means min 3 and max 6 digit of decimal points at the end.

Tam
  • 3,153
  • 3
  • 30
  • 50