How can I validate for a unique email address?

I was trying to have my form validate an email address onblur or onkeyup, to check to see if the email address already exists in my database.

Not sure if I'm almost there with this code, something isn't working though. Right now, as soon as I start typing in the field, the input box for email is flagged based on how I would want it flagged if an email address was entered if it was already in my database. The else statement in AJAX doesn't work, and if I submit the form anyway, I get a message on the page from an error box I created mentioning a syntax error.

Also, part of my php is using mysqli and mysql, does that make a difference with trying to get this input field to validate?

The input id is email and the name is Email; I think I have that correct in my code, not entirely sure though.

PHP:

define('DB_NAME', 'database');
define('DB_USER', 'user');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'host');

$first = Trim(stripslashes($_POST['First']));
$last = Trim(stripslashes($_POST['Last']));
$city = Trim(stripslashes($_POST['City']));
$state = Trim(stripslashes($_POST['State']));
$country = Trim(stripslashes($_POST['Country']));
$email = Trim(stripslashes($_POST['Email']));
$tempt = $_POST['tempt'];
$tempt2 = $_POST['tempt2'];


$link = mysqli_connect('host','user','password','members') or die("Error " . mysqli_error($link)); 
$stmt = mysqli_prepare($link, 'SELECT count(*) FROM members WHERE email =?');
mysqli_stmt_bind_param($stmt, 's', $_POST['Email']);
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $count);
/* fetch value */
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);

if ($count == 0) {
    echo 'true';
}else{
    echo 'false';
}


if ($tempt == 'http://' && empty($tempt2)) {

    $error_message = '';
    $reg_exp = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9­-]+.[a-zA-Z.]{2,5}$/";

    if(!preg_match($reg_exp, $email)) {

        $error_message .= "<p>A valid email address is required.</p>";
    }
    if (empty($first)) {
        $error_message .= "<p>Please provide your first name.</p>";
    }
    if (empty($last)) {
        $error_message .= "<p>Please provide your last name.</p>";
    }

AJAX:

$(function() {
    if (valid != '') {
    $('form #response2').removeClass().addClass('error2')
        .html('' +valid).fadeIn('fast');
}

    var valid = '';

    $('#email').keyup(function() {
        $.post('script.php', { 'Email' : $(this).val() }, function(data) {
             if(data !== 'true') {
                $('#email').css('border','2px solid #ff0000');
                $('#email').css('background-color','#ffcece');
                valid += '<p>This email has already subscribed.</p>';
             }else{
                $('#email').css('background-color','green');
             }
        });
    });
});
链接地址: http://www.djcxy.com/p/69752.html

上一篇: 我如何正确验证一个唯一的电子邮件地址?

下一篇: 我如何验证唯一的电子邮件地址?