1

In this form, when I add a new ingredient, it works for any number, no matter if it's positive or negative.

So, if I add 'Bread with amount 5' it will show this:

enter image description here

If I add 'Bread with amount -5' it will show this:

enter image description here

I tried to use this pattern validator: pattern="^[1-9]+[0-9]*$"

enter image description here

But now the 'Add' button is disabled, no matter if I want to add positive or negative numbers...

enter image description here

Any idea why this is not working?

Quentin
  • 1,865
  • 2
  • 24
  • 40
Sorin
  • 31
  • 4

2 Answers2

3

You are applying Pattern on Name field. Apply it on Number field.

Taimoor Tahir
  • 430
  • 4
  • 6
1

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
Brook Jordan
  • 1,223
  • 10
  • 18