1

So I have some forms with html input validations like so:

<input type="number" min="1" max="50" ...

Now I need to add some custom ranges such as 1-40, 45, & 50. Previously I've just wrote javascript to handle this but would rather just use the html input validation. Is there any way to achieve this other than checking with javascript / jquery ?

I think i can use <input pattern="regularExp" ... This could also be an option but I have no experience in it...

Thanks

JayD
  • 6,173
  • 4
  • 20
  • 24

1 Answers1

1

In addition to min and max, HTML5 gives you the step attribute. For example, <input type="number" min="1" max="50" step="10"> gives you acceptable values of 1, 11, 21, 31, and 41. Beyond those three attributes, there is JavaScript.

If you really do not want to use JavaScript, then you can try to use a regular expression with the pattern attribute of the input element. Note that the pattern attribute requires that your input type be set to text instead of to number and include a title that is used to describe the pattern. Also note that regular expressions are meant for parsing text character by character, which makes it difficult to deal with numbers beyond a single digit.

Here's an example that allows 1-40, 45, and 50 (but not if the number is preceded by a zero):

<input type="text" name="example-number"
 pattern="(^40$)|(^45$)|(^50$)|(^1[0-9]$)|(^2[0-9]$)|(^3[0-9]$)|(^[1-9]$)" 
 title="A number in the range of 1-40, 45, or 50">

Plenty of people recommend using code (e.g., JavaScript) instead of a regular expression for validating numeric ranges, which may be why an entire site dedicated to input patterns does not have any listed for numeric ranges.

Community
  • 1
  • 1
schellack
  • 10,144
  • 1
  • 29
  • 33
  • 1
    If you want to see how that particular RegEx works, check out http://regexr.com/38tga – schellack May 27 '14 at 20:32
  • Thanks for the lengthy response. I've used javascript for this in the past.. I was jsut curious because most of my validation messages on the site are from the native html input validation and i did not want to take the time to recreate the message in the sake of "uniformity".. was just looking for a work around... thanks for your time... PS ur a beast – JayD May 27 '14 at 20:36
  • 1
    `^` matches the beginning of a string. `$` matches the end of a string. `|` is the symbol for "or". The parenthesis are not really needed, but help illustrate the logical groupings. If you want to shorten the pattern, you could probably use `pattern="^(40|45|50|1[0-9]|2[0-9]|3[0-9]|[1-9])$"` instead. `[1-9]` matches a single character in the range of 1 through 9. When specified, the preceding digit (`1`, `2`, or `3`) looks for that exact character, so that we can find number in the tens, twenties, or thirties. – schellack May 27 '14 at 21:13