我需要电子邮件验证方面的帮助,这个验证码所有的电子邮件都是特定格式的,例如test@test.gov.au,test@something.ac.au,我希望它的格式为test@something.au < / p>
(注意:这里我只允许进入5个域名,即gov.au,edu.au,govt.nz,ac.au和csiro.au)
我的代码如下
JS:
function emailTldValidation(tlds) {
$.validator.addMethod("emailTld", function(value,element) {
if (value.search("@") != -1) {
return (/(.+)@(.+)\.(gov\.au|edu\.au|ac\.nz|csiro\.au|govt\.nz)$/).test(value);
//return (/(.+)@(.+)\.(csiro\.au|gov|gov\.us)$/).test(value);
}
return false;
},"Please enter valid tld like "+tlds);
$.validator.addClassRules({
stringInput: {
emailTld: true
}
});
}
以下代码在function.php中验证
function validateEmail($email) {
//validate email here from server side
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//validate tld
$validTlds = str_replace(".", "\.", VALID_EMAIL_TLDS);
$validTlds = "\.".str_replace(",", "|\.", $validTlds);
$emailArr = explode("@", $email);
$emailTld = $emailArr[1];
if (preg_match('/^[-a-z0-9]+\.[a-z][a-z]|('.$validTlds.')\z/', strtolower($emailTld))) {
//check main domain here
$exValidTlds = explode(",", VALID_EMAIL_TLDS);
$exValidTlds = array_map('trim', $exValidTlds);
foreach($exValidTlds as $tld) {//if exist then
if(strstr($emailTld, ".".$tld)) {
if($tld == strrchr($emailTld, $tld)) {
return true;
}
}
}
return false;
}
}
答案 0 :(得分:0)
function validateEmail($email) {
//validate email here from server side
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//validate tld
$validTlds = str_replace(".", "\.", VALID_EMAIL_TLDS);
$validTlds = "\.".str_replace(",", "|\.", $validTlds);
//$validTlds = str_replace(",", "|\.", $validTlds);
$emailArr = explode("@", $email);
$emailTld = $emailArr[1];
if ($emailTld == 'csiro.au')
{
//check main domain here
return true;
}
elseif (preg_match('/^[-a-z0-9]+('.$validTlds.')\z/', strtolower($emailTld))) {
//check main domain here
$exValidTlds = explode(",", VALID_EMAIL_TLDS);
$exValidTlds = array_map('trim', $exValidTlds);
foreach($exValidTlds as $tld) {//if exist then
if(strstr($emailTld, ".".$tld)) {
if($tld == strrchr($emailTld, $tld)) {
return true;
}
}
}
return false;
}
}
return false;
}
这个正则表达式对我来说非常好:
.+@(?:(?:govt*)|(?:edu)|(?:ac)|(?:csiro))\.(?:au|nz)
我使用此工具创建它:http://regexpal.com/
仅供参考,验证电子邮件难以置信困难:http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html
编辑:重新阅读您的问题后,您似乎可能需要验证包含子域名的电子邮件等。这可能更适合更开放的域名:
.+@(?:\w+\.\w+)
编辑2:问题是你的验证太复杂了。
.+@(?:(?:.+\.(?:(?:govt*)|(?:edu)|(?:ac))\.(?:au|nz))|(?:csiro\.au))
打破它:
.+ // Match at least 1 of any character
@ // An @ symbol
(?: // The group of everything right of the @ symbol
(?: // The group of domains that have subdomains
.+\. // At least one character in front of a .
(?: // govt, edu or ac
\. // a dot
(?: // au or nz
(?: // or simply 'csiro.au'
你无法解决这样一个事实:你的四个域需要一个子域,而另一个域则不需要。