While creating any contact us form we ask users from phone number, similarly we may need phone number in E-comerce website while placing order, so to get the phone number it is important to validate the phone number before saving it into database using client side validations & in this article, I will show you how you can implement phone number validation using HTML5 without using jQuery or Javascript.

HTML5 includes a fairly solid form validation mechanism powered by the following <input /> attributes: type, pattern, and require. Thanks to these new attributes in HTML5, you can delegate some data verification functions to the browser.

We can test or validate user input with the help of pattern attribute which makes a lot of front-end developers work easy. This attribute specifies a format (in the form of a JavaScript Regular Expression) that the field value is checked against.

I have also added how you can validate Email using HTML5 in similar way.

So, to begin with, to validate a phone number with a regular expression (regex), we will use type and pattern attribute in HTML input field.

HTML5 Phone number validation using Regex

The following example code validates a phone number and checks whether the user provided a phone number in the correct format (xxx-xxx-xxxx).

<form>
  Phone Number (format: xxx-xxx-xxxx):
  <input type="tel" pattern="^\d{3}-\d{3}-\d{4}$" required>
  
  <input type="submit" value="Submit">
</form>

Now, for example, the regex validation for india should make sure that +91 is used, then make sure that 7, 8,9 is used after +91 and finally followed by 9 digits.

<form>
  <h2>Phone Number Validation</h2>
  <label for="phonenum">Phone Number:</label><br/>
  <input id="phonenum" type="tel" pattern="^\+91(7\d|8\d|9\d)\d{9}$" required >
  
  <input type="submit" value="Submit">
</form>

html5-phone-number-validation-min.png

Another example, to check code whether the user provided 10 digits numeric value (xxxxxxxxxx)

<form>
  Phone Number (format: xxxxxxxxxx):
  <input type="tel" pattern="^\d{10}$" required >
  
  <input type="submit" value="Submit">
</form>

HTML 5 Email validation using regex

We can easily use the same HTML5 pattern attribute to validate email by creating regex for it, here is one example for it

<form>
  <h2>Email validation</h2>
  <label for="email">Enter Email</label><br/>
 <input type="email"
  pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,63}$" required />
  
  <input type="submit" value="Submit">
</form>

Note: You should work always perform server-side validation also.