Home > Software engineering >  HTML input element won't match pattern
HTML input element won't match pattern

Time:01-20

I am having issues with getting a "Phone Number" input validated. I have written the regex pattern to require 10 numbers, but even when I plug in 10 numbers into the input field, I still get the error message: "Please match the requested format" and can't seem to figure out why this is.

All help and advice is greatly appreciated!


<input type="text" id="number" name="number" pattern="/^\d{10}$/" required>
                   

CodePudding user response:

Here is a code example from this page: https://www.w3schools.com/html/html_form_input_types.asp

You can directly do it with an in-build functionality of HTML. Just use the type type="tel" and you should be good to go. if you want 10 consecutive numbers without - you can also do: pattern="[0-9]{10}"

<form>
         <label for="phone">Enter your phone number:</label>
         <input type="tel" id="phone" name="phone" pattern="[0-9]{3}-[0-9]{2}-[0-9]{3}">
</form> 

Just place you're input in a <form> and hit submit. It should now match.

CodePudding user response:

I don't believe you need the forward slashes in your regex pattern here. Try this: <input type="text" id="number" name="number" pattern="^\d{10}$" required>

  • Related