-1

if an email is in the format

firstname.lastname@gmail.com

coditions to check via the regex :

email has only 1 @

firstname.lastname

at the very end its either a .com or .net or .co.in

it should not accept emails like abcdef@tcs.xyz

but should accept abc.def@tcs.com or tcs.co.in

var empmail = 'charles.x.markus.bukowski@company.com'
var fullName = empmail.split('@')[0].split('.');
var firstName = fullName[0];
var lastName = fullName[ fullName.length-1 ] ;
var fullName = empmail.split('@')[0].split('.');

1 Answers1

0

I believe you could try:

/^[^@]+\.[^@]+@[^@]+\.(com|net|co\.in)$/

let pattern = /^[^@]+\.[^@]+@[^@]+\.(com|net|co\.in)$/;
let testEmails = [
    "abc.def@tcs.co.in",
    "abc.def@tcs.co.uk",
    "abc.def@tcs.com",
    "abc.def@tcs.net",
    "abc.def@tcs.xyz",
    "charles.x.markus.bukowski@company.com",
    "firstname.lastname@gmail.com",
    "name@gmail.com",
    "lastname@test@gmail.com"
];    
for (let i = 0; i < testEmails.length; i++) {
    console.log(`Email ${testEmails[i]}: ${pattern.test(testEmails[i])}`);
}
^

Start matching from the beginning of the string

[^@]+

One or more characters except @

\. 

Followed by a dot

[^@]+

Followed by one or more characters except @

@

Followed by @

[^@]+

Followed by one or more characters except @

\.

Followed by a dot

(com|net|co\.in)$

With the string ending in com, net, or co.in

If you want to restrict the input further so that there is only one dot in the firstname.lastname portion, you can change [^@] to [^@\.]

/^[^@\.]+\.[^@\.]+@[^@]+\.(com|net|co\.in)$/

let pattern = /^[^@\.]+\.[^@\.]+@[^@]+\.(com|net|co\.in)$/;
let testEmails = [
    "abc.def@tcs.co.in",
    "abc.def@tcs.co.uk",
    "abc.def@tcs.com",
    "abc.def@tcs.net",
    "abc.def@tcs.xyz",
    "charles.x.markus.bukowski@company.com",
    "firstname.lastname@gmail.com",
    "name@gmail.com",
    "lastname@test@gmail.com"
];    
for (let i = 0; i < testEmails.length; i++) {
    console.log(`Email ${testEmails[i]}: ${pattern.test(testEmails[i])}`);
}
Kei
  • 1,026
  • 8
  • 15