Jquery电子邮件验证

时间:2011-08-07 17:11:14

标签: php jquery

在获得@juhana的帮助后(再次感谢你)我最终用theese代码来验证电子邮件输入:

验证电子邮件:

function validateEmail(){
var a = $("#email").val();
  $.ajax({
  type: "POST",
  url: "check_email.php",
  data: "email="+a,
  success: function(rsp){
   //if it's valid email
   if(rsp == "ok"){
    email.removeClass("error");
    emailInfo.text("");
    emailInfo.removeClass("error");
    return true;
}

else
//if it exists
if(rsp == "exists" ){
 email.addClass("error");
 emailInfo.text("E-mail already in use");
 emailInfo.addClass("error");
 return false;
}

else
//if it's NOT valid
if(rsp == "invalid"){
 email.addClass("error");
 emailInfo.text("Please type a valid E-mail");
 emailInfo.addClass("error");
 return false;
 }
}
});
}

check_email.php

<?php
require_once('db_conn.php');
require_once('is_email.php');

$email = mysql_real_escape_string($_POST['email']);
if (is_email($_POST['email'])){
echo 'ok';

$checkemail = mysql_query("SELECT E_mail FROM orders WHERE E_mail='$email'");
$email_exist = mysql_num_rows($checkemail);

if($email_exist>0){
echo 'exists';
}
}else{
echo 'invalid';
}
?>

现在有3个人正在使用“ok”和“无效”......“存在”没有。

这里有什么问题???

谢谢

2 个答案:

答案 0 :(得分:1)

通过阅读上面的代码,如果电子邮件有效但存在于数据库中,则会返回“okexists”,这会导致您的javascript失败。您需要将其更改为以下内容:

<?php

$email = mysql_real_escape_string($_POST['email']);
$checkemail = mysql_query("SELECT E_mail FROM orders WHERE E_mail='$email'");
$email_exist = mysql_num_rows($checkemail);

    if (is_email($_POST['email'])){
        if($email_exist) {
            echo "exists";
        }
        else {
            echo "ok";
        }
    } else {
        echo "invalid";
    }

?>

这允许它在有效但现有的电子邮件中仅返回令牌“存在”。并且只有标记“ok”,当它是有效的,而不是以前存在的电子邮件时。当然,如果它没有通过is_email()测试,它将返回无效。

答案 1 :(得分:0)

var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
var email= $("#emailid").val();
if(!filter.test(email)){
        alert('Plz enter valid email id');
        return false;
    }