SyntAx
SyntAx

Reputation: 63

how to make the pattern to work with input number?

This is my first time using the pattern attribute. The following code is inside a <form> tag:

<input type="number" name=""  placeholder="Number" pattern=".{12,13}" required>

I expect the pattern to make the number has minimal of 12 numbers and a max of 13 numbers. However, I can still submit the form with less than 12 numbers.

Upvotes: 3

Views: 121

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50684

You can't use the pattern attribute on inputs of type number:

<input type="number"> elements do not support use of the pattern attribute for making entered values conform to a specific regex pattern. The rationale for this is that number inputs won't be valid if they contain anything except numbers, and you can constrain the minimum and maximum number of valid digits using the min and max attributes

- MDN

As explained on MDN, you can use the min and max attributes to specify your domain:

<form>
  <input type="number" name="number" placeholder="Number" min="100000000000" max="9999999999999" required />
  <input type="submit" />
</form>

Alternatively, you can use an input type of text (which does allow pattern), and match for digits (\d):

<form>
  <input type="text" name="number" placeholder="Number" pattern="\d{12,13}" inputmode="numeric" title="Your number must be 12-13 digits long" required />
  <input type="submit" />
</form>

Upvotes: 4

Related Questions