Home > Back-end >  How I use Regex pattern in HTML text input to validate phone number
How I use Regex pattern in HTML text input to validate phone number

Time:04-21

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"  pattern ="(?:7|0|(?:\ 94))[0-9]{9,10}$" required />

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

CodePudding user response:

You could try this:

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

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

CodePudding user response:

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"  pattern="(?:7|0\d|\ 94\d)\d{8}" required />
  <input type="Submit"/>
</form>

CodePudding user response:

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"  placeholder="Phone number" pattern ="(7[0-9]{8}|0[0-9]{9}|\ 94[0-9]{9})$" required />

  • Related