0

I have to validate input text field as a phone number field. To do that I'am going to use HTML5 validation.

I already wrote code like this:

<input maxlength="8" type="text" name="phone" required />

I used required to validate this form. But how to validate this for Enter only digits and 8 digits.

0

3 Answers 3

2
<input maxlength="8" pattern="\d{8}" type="tel" name="phone" required />
Sign up to request clarification or add additional context in comments.

Comments

2

Use pattern.

<input type="text" pattern="\d{8}" />

\d is the regular expression for a number.

5 Comments

Only correct answer here... would like to suggest you that you can also use type="number" for better semantic meaning as anyways you are using pattern to validate
@Mr.Alien any reason for using type="number" as opposed to type="tel" which is semantically specific to phone numbers?
@MyHeadHurts Oh I missed the phone word, just went with number as written here Enter only digits and 8 digits
This allows any number of digits, not 8, as requested.
Suggesting type="number" for a telephone number is wrong, and it violates the recommendation of the very drafts that define type="number" in the first place.
0

You can set the Type="tel" but this not validates everything. You can use the pattern attribute with an regex.

The input-patter support:

Pattern Support Firefox 4+ & Chrome 5+ & Opera 9.6+ & MSIE 10+

For example:

<input type="tel" pattern="[0-9]*([-]?[0-9]+)*" >

For the 8 diggets you can use the maxlength="8"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.