0

I'm trying to figure out the javascript regex validator that checks first whether the string appears to be a valid email address and second whether there are 10 and only 10 numbers before the @ sign. I have come up with this:

/[0-9]\@+@\S+\.\S+/

...but that's not right. I have been looking at this stack post, but can't quite figure out how to combine the numeric checks before the @ with the email validator.

Ultimately I need a function that returns true if the string matches my pattern, and false otherwise. Thanks in advance.

Example string: 8015551234@foobar.com

HerrimanCoder
  • 6,835
  • 24
  • 78
  • 158

2 Answers2

2

var r = /^\d{10}@\S+\.\S+$/,
    a = [
          '801555123@foobar.com',   // Too short
          '80155512341@foobar.com', // Too long
          'notNumbers@foobar.com', 
          '8015551234@foobar.com'   // Just right
        ]

a.forEach(function(s) {
  console.log(r.test(s))
})

Explanation

  • ^ Assert position at the start of the line
  • \d{10} Match exactly 10 digits
  • @ Match this literally
  • \S+ Match one or more non-whitespace characters
  • \. Match a dot literally
  • \S+ Match one or more non-whitespace characters
  • $ Assert position at the end of the line
ctwheels
  • 21,901
  • 9
  • 42
  • 77
0

Use the following RegEx:

/(?<=(\s|^))[0-9]{10}\@+[a-zA-Z0-9_.-]+/

See the live demo (Regex101).

If you do not require whitespace before the digit sequence (ie. if these digits needn't make up the whole local name [part before the @]) drop the lookbehind part ((?<=\s*))

Explanation

  • Checking for 10 digits before the @.
  • Checking for a whitespace character or the start of the string before the number portion using negative lookbehind.
  • Checking for a syntactically well-formed domain name after the at sign

Notes

  • 'Syntactically well-formed' should be understood as absolutely low-level: Domain names are subject to various constraints that are not validated (eg. ending with a top-level domain). Regexen would be the wrong tool for this.

  • The check for the domain portion does not cater for internationalised domain names. Have a look at this SO answer to get an idea.

Code Embedding

Turn the regex into a test code as follows:

[
      '123456789@example.com            '
    , '12345678901@example.com          '
    , 'a1234567890@example.com          '
    , 'whatever@example.com             '
    , '1234567890@example.com           '
    , '1234567890@gargamel.smurf.com    '
    , ' 1234567890@a.strange.domain.name.but.hey.if.it.gets.resolved....org'     
].map ( function ( sample ) {
    return /(?<=(\s|^))[0-9]{10}\@+[a-zA-Z0-9_.-]+/.test(sample);
}); 
collapsar
  • 17,010
  • 4
  • 35
  • 61