6

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
4
  • @Wiktor Stribiżew .. where is my answer? please read question completely before mark as duplicate Commented Jun 22, 2018 at 7:19
  • @Wiktor Stribiżew now i edit my question Commented Jun 22, 2018 at 7:38
  • Try pattern="[1-4](?:\.\d+)?|5(?:\.0+)?" Commented Jun 22, 2018 at 7:42
  • Thanks.. its works perfectly Commented Jun 22, 2018 at 8:01

1 Answer 1

4

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+)?)"
         ^^^^^                          ^       
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.