Home > Back-end >  Regex to match email username except for 10 consecutive digits (or 11 if it starts with 1)
Regex to match email username except for 10 consecutive digits (or 11 if it starts with 1)

Time:01-16

I need a regex for my email validator. I do not want to allow users to enter whole phone numbers as email username. If the user enters all numbers:

[email protected] // allowed (9 digits or less)
[email protected] // allowed (11 digits but not starting with 1)
[email protected] // allowed (12 digits or more)

[email protected] // NOT allowed (10 digits)
[email protected] // NOT allowed (11 digits and starting with 1)

There is a great close answer here which I tried

<input 
    type="email" 
    pattern="(?:^|(?<=\s))(?!\d{10}|1\d{10})(\w[\w\.]*@\w \.[\w\.] )\b"
/>

But the exclude part (?!\d{10}|1\d{10}) does not work for me. I want to allow 12 or more digits.

Thanks

CodePudding user response:

You can try adding a negative lookahead to your regex as shown below:

(?:^|(?<=\s))(?!1?\d{10}@)(\w[\w\.]*@\w \.[\w\.] )\b 
             -------------

Click for Demo

I have just added the subpattern (?!1?\d{10}@) to your regex which does not allow the current position to be followed by (an optional digit 1 followed by 10 more digits followed by @)

  •  Tags:  
  • Related