validate email addresses using a regex.
This question already has an answer here:
Don't bother, there are many ways to validate an email address. Ever since there are internationalized domain names, there's no point in listing TLDs. On the other hand, if you want to limit your acceptance to only a selection of domains, you're on the right track. Regarding your regex:
.
matches almost anything, .
matches “.” [w-]
(without dot) which won't work for “@mail.example.com”. I like this one: /^.+@.+...+$/
It tests for anything, an at sign, any number of anything, a dot, anything, and any number of anything. This will suffice to check the general format of an entered email address. In all likelihood, users will make typing errors that are impossible to prevent, like typing john@hotmil.com
. He won't get your mail, but you successfully validated his address format.
In response to your comment: if you use a non-capturing group by using (?:…)
instead of (…)
, the match won't be captured. For instance, all email addresses have an at sign, you don't need to capture it. Hence, (john)(?:@)(example.com)
will provide the name and the server, not the at sign. Non-capturing groups are a regex possibility, they have nothing to do with email validation.
上一篇: 正则表达式匹配DNS主机名或IP地址?
下一篇: 使用正则表达式验证电子邮件地址。