Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email verification in JavaScript

I have to implement email verification such that Email addresses cannot start or end with a dot.

The code is as below:

function validateEmail(elementValue)
{
   var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

   return emailPattern.test(elementValue);
}
like image 284
Amit Raj Avatar asked Mar 02 '26 22:03

Amit Raj


2 Answers

The simplest JavaScript-compatible change you could make to ensure that it does not start with a period/dot/decimal-point would be to use a negative lookahead like so: (?!\.) at the beginning of the expression:

function validateEmail(elementValue)
{
   var emailPattern = /^(?!\.)[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

   return emailPattern.test(elementValue);
}

There are plenty of cases this does not handle, and depending upon your reasons for this need, it might be one of thousands of things that go into creating a perfect RFC-2822 compliant email address (which I don't believe actually exists in any commercially viable system or "in the wild") - that you don't really need to worry about.

you could also simplify it further by making it case-insensitive:

/(?!\.)[a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,4}/i

or even better...

/(?!\.)[\w.-]+@[a-z0-9.-]+\.[a-z]{2,4}/i

and you might want to consider (if you haven't already) the .travel and .museum TLDs that would be invalidated by your {2,4} length limitation

like image 100
Code Jockey Avatar answered Mar 04 '26 10:03

Code Jockey


var emailAddressPattern = /(((\s*([^\x00-\x1F\x7F()<>[]:;@\,."\s]+(.[^\x00-\x1F\x7F()<>[]:;@\,."\s]+))\s)|(\s*"(([^\"])|(\([^\x0A\x0D])))+"\s*))\@((\s*([^\x00-\x1F\x7F()<>[]:;@\,."\s]+(.[^\x00-\x1F\x7F()<>[]:;@\,."\s]+))\s)|(\s*[(\s*(([^[]\])|(\([^\x0A\x0D])))+)\s]\s*)))/;

like image 41
RHT Avatar answered Mar 04 '26 11:03

RHT