这是我的代码。
function emailField($email)
{
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
和
if(emailField($_POST['email'])=='')
{
echo "Invalid email";
}
else
{
echo "Valid";
}
允许使用所有特殊字符。我想只允许下划线,连字符和点。如何避免?
使用RegEx:
/^['w'.]+@/
那么你还应该检查这个域是否真的存在。
PHP:$regex = "/^['w'.]+@/";
$email = emailField($_POST['email']);
$domain = preg_replace($regex, '', $email); //get the domain of the email address by removing the local-part
//Using checkdnsrr we are checking if this domain is registred
if($email == '' && preg_match($regex, $email) && checkdnsrr($domain)){
echo "Valid";
}
参见:http://php.net/manual/en/function.checkdnsrr.php
同时使用复杂的filter_var
验证和简单的preg_match
验证
function validate_email_popularly($email) {
return
filter_var($email, FILTER_VALIDATE_EMAIL)
&& preg_match('/'A['w.-]*+@['w.-]*+'z/', $email)
;
}
你也应该用filter_input
代替$_POST
。该函数可以过滤未预料到的Notice: Undefined index or Array
into False
.
$email = filter_input(INPUT_POST, 'email');
echo validate_email_popularly($email) ? 'Valid' : 'Invalid';