Regex that allow empty

lenamtl
lenamtl used Ask the Experts™
on
Is this possible to allow empty field to this regex verification?
This is an email field javascript verification, this field is not mandatory
So if I don't fill this field I got 'Email address is not correct'

var ad = new RegExp("^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$");
    if (!ad.test(f.email.value)) {
      jAlert("Email address is not correct.");
      return false;
    }

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
IT Guru
Most Valuable Expert 2011
Commented:
This should do it:
var ad = new RegExp("^(([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6})?$");
    if (!ad.test(f.email.value)) {
      jAlert("Email address is not correct.");
      return false;
    }

Open in new window

leakim971Multitechnician
Top Expert 2014

Commented:
or :


var ad = new RegExp("^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$");
    if (!ad.test(f.email.value) && (f.email.value.length!=0)) {
      jAlert("Email address is not correct.");
      return false;
    }

Open in new window

Terry WoodsIT Guru
Most Valuable Expert 2011

Commented:
I took the part of the pattern between the ^ and the $ and put round brackets around it, and then added a ? to make the entire pattern optional.
Thanks a lot this is working ok,
Thanks for the extra explanation that will help me to understand  other regex in the futur.


Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial