4

I would like to restrict a text input field in a HTML5 form. I need it only value from 1 to 5

My code is

 <input type="text" name="count" pattern="[1-5][0-9-.]{1,10}" value="1" required>

Do match (Expectation):

1
1.5
1.584
2
4.68756
5

Don't match (Expectation):

0
.5
0.99
01
05
5.1
6
[a-zA-Z] and other special characters

Now happened (the problem):

  • Not validate non decimal values (1,2,3,4 and 5).
  • Validates 5.1 to 5.9
Rafeeq Mohamed
  • 182
  • 1
  • 4
  • 14

1 Answers1

2

You may use

pattern="[1-4](?:\.\d+)?|5(?:\.0+)?"

It gets parsed as ^(?:[1-4](?:\.\d+)?|5(?:\.0+)?)$ by HTML5 engine. See the regex demo.

Details

  • ^(?: - start of string and start of a non-capturing group
  • [1-4] - a digit from 1 to 4
  • (?:\.\d+)? - an optional sequence of . and 1+ digits (fractional part may contain any number of any digits)
  • | - or
  • 5 - matches 5
  • (?:\.0+)? - an optional sequence of . and 1+ zeros (fractional part may contain any number of zeros if the whole part is 5)
  • )$ - end of the outer "container" group and end of string.

To allow leading zeros, use

pattern="0*(?:[1-4](?:\.\d+)?|5(?:\.0+)?)"
         ^^^^^                          ^       
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563