Reputation: 2340
What could be the Regex for accepting .@.
as a valid email id? Also need to check the below conditions.
Should contain exactly one @
character.
Before and after @
should consist of at least 1 and at most 64 characters comprising only letters, digits and/or dots(a-z, A-Z, 0-9, .)
.
was trying with \b[\w\.-]+@[\w\.-]+\.[\w]{0,0}
but not working as expected.
Upvotes: 1
Views: 9369
Reputation: 25634
/^[a-z0-9.]{1,64}@[a-z0-9.]{1,64}$/i
should do the trick (Regex101 explanation):
function demo(str) {
const isEmail = /^[a-z0-9.]{1,64}@[a-z0-9.]{1,64}$/i.test(str);
console.log(isEmail, str);
}
demo('.@.'); // OK
demo('[email protected]'); // OK
demo('a-b_c@a_b'); // Bad chars
demo('a.b.c'); // No @
demo('1234567890123456789012345678901234567890123456789012345678901234@a'); // OK
demo('12345678901234567890123456789012345678901234567890123456789012345@a'); // Too long
Upvotes: 4
Reputation: 6872
Should contain exactly one @ character.
Before and after @ should consist of at least 1 and at most 64 characters comprising only letters, digits and/or dots(a-z, A-Z, 0-9, .).
You don't need regex for that:
const validateEmail = (email) => {
const parts = email.split('@');
if (parts.length !== 2) {
// Either no @ or more than one
return false;
}
const [before, after] = parts;
return (
before.length > 0 &&
before.length <= 64
) && (
after.length > 0 &&
after.length <= 64
);
}
console.log(
validateEmail('.@.'),
validateEmail('[email protected]'),
validateEmail('wrong@'),
validateEmail('this@is@wrong'),
);
Using regex would be overkill, and will likely be a lot slower than performing 1 split, and 3 equality checks.
Upvotes: 0