Your pattern will work. However, I think it's worth bringing up three points:
1) Most importantly, as pointed out by Mian Taimoor Tahir, you are currently applying the pattern to the wrong input.
2) That said, a simpler pattern would be:
[1-9]\d*
3) And lastly, although your question specifically mentioned "How to use the pattern validator…", I think it's worth having the same answer here in case other people are also attempting to use the pattern attribute.
That is: inputs can use type="number"
along with the min=1
and step=1
parameters, also mentioned by Nicholas K.
That would look something like this:
<input type="number" min="1" step="1">
This would be a preferable way to solve your problem for the following reasons:
- it's an easier-to-understand API for developers to update
- The browser stepper will be inserted, making it clear that this is a number input
- it will bring up a nicer keyboard for many mobile users
- it will prevent accidental, hard to see, errors such as putting the letter O in the input
- if support is a concern, more browsers (I believe) support the number input than the pattern attribute