Search code examples
regexemail-validation

Regex to match email username except for 10 consecutive digits (or 11 if it starts with 1)


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:

123456789@test.com // allowed (9 digits or less)
01234567890@test.com // allowed (11 digits but not starting with 1)
123456789012@test.com // allowed (12 digits or more)

0123456789@test.com // NOT allowed (10 digits)
11234567890@test.com // 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


Solution

  • 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 @)