'How I use Regex pattern in HTML text input to validate phone number

My number format as shown in the below:

1. 775645645 (9 digits)

2. 0775645645 (10 digits)

3. +94775645645

The numbers can start with 7 or 0 or +94.

So I tried it with regex pattern in HTML text input as shown in the below:

<input type="text" name="mobile" class="form-control" pattern ="(?:7|0|(?:\+94))[0-9]{9,10}$" required />

But this pattern is not working for me. Appreciate your help.

UPDATE:

Here Im using jQuery validate to validate a front end form.



Solution 1:[1]

You can use

pattern="(?:7|0\d|\+94\d)\d{8}"

See the regex demo. It will be compiled into a pattern like ^(?:(?:7|0\d|\+94\d)\d{8})$ and will match

  • ^(?: - start of string and the non-capturing group start
  • (?:7|0\d|\+94\d) - 7, or 0 and a digit or +94 and a digit
  • \d{8} - eight digits
  • )$ - end of the group, end of string.

See the demo below:

input:valid {
  color: navy
}
input:invalid {
  color: red;
}
<form>
  <input type="text" name="mobile" class="form-control" pattern="(?:7|0\d|\+94\d)\d{8}" required />
  <input type="Submit"/>
</form>

Solution 2:[2]

Can try this hope it helps

  • if it starts with 7, the length must be 9 digits
  • if it starts with 0, the length must be 10 digits
  • if it starts with +94, the length must be 12 digits

input:not(:placeholder-shown):invalid{
  background-color:pink;
  box-shadow:0 0 0 2px red;
}
<input type="text" name="mobile" class="form-control" placeholder="Phone number" pattern ="(7[0-9]{8}|0[0-9]{9}|\+94[0-9]{9})$" required />

Solution 3:[3]

If you are looking for a regex pattern that only works for your examples try this:

(?:(?:7|0[1-9]{1})|(?:\+94))[0-9]{8}
  • 7|0[1-9]{1} accepts 7 or 0 and one other digit between 1-9
  • the | is used to represent the "OR" condition
  • \+94 accepts +94 as the 3 beginning digits
  • [0-9]{8} means 8 other digits between 0 and 9

If you are looking for a pattern that could work for a wide range of phone number patterns, you could try this:

^[+]?[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$

How this works:

  • ^ represents the beginning of the string
  • [+]? for phone numbers that include "+" at the beginning
  • [(]{0,1} represents the opening " ( ". For phone numbers that include (###). Example: (222)333-333
  • [0-9]{1,4} represent the number in between the "(###)"
  • [)]{0,1} represent the closing ")"
  • [-\s\./0-9]* this will allow phone numbers to be accepted even if the numbers are divided using "-" or " " or "."
  • $ represents the end of the string

Check this site: https://regexr.com/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Diki Agustin
Solution 3