avieira
avieira

Reputation: 3

Validate Dynamically Form Data

I have a form field in my site that I need to know if the email that the user want to use isn't already used by other user.

I am using JavaScript and PHP for that but can make it work.

function validateEmail(){
    //testing regular expression
    var a = $("#email").val();
    var filter = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/;
    //if it's valid email
    if(filter.test(a)){
        if($("#email").val() != ""){
            $.getScript("http://localhost/sisdelivery/validaEmail.php?&email="+$("#email").val(), function(){
                if(resultadoEmail["email"] != ""){
                    email.addClass("error");
                    emailInfo.text("Email ja cadastrado!");
                    emailInfo.addClass("error");
                    return false;
                }
                else{
                email.removeClass("error");
                emailInfo.text("Email OK");
                emailInfo.removeClass("error");
                return true;
                }
            }
        }
    }
    //if it's NOT valid
    else{
        var valEmail = $("#email").val();
        if(valEmail == ""){
            email.addClass("error");
            emailInfo.text("Favor digitar um email!");
            emailInfo.addClass("error");
            return false;
        }
        else{
            email.addClass("error");
            emailInfo.text("O email digitado e invalido");
            emailInfo.addClass("error");
            return false;
        }
    }
}

The PHP code that looks on the database for the data:

<?php
include "conecta.php";
$email = $_GET['email'];

$consulta = "SELECT * FROM usuarios WHERE email = '$email';";
$result = mysql_query($consulta);
$num = mysql_num_rows($result);

if($num == 0)
    echo "var resultadoEmail = { 'email' : '' }";

else{
    while($row = mysql_fetch_object($result)){
        $email = $row -> email;
    }
    echo "var resultadoEmail = { 'email' : '$email' }";
}
?>

I'm getting the error Uncaught SyntaxError: Unexpected token } but can't find where is the problem.

Upvotes: 0

Views: 103

Answers (2)

Bertrand
Bertrand

Reputation: 388

First of all, I just want to tell you that you have a security risk in your code. This line :

$email = $_GET['email'];
$consulta = "SELECT * FROM usuarios WHERE email = '$email';";

allow a person to run sql against your database and retrieve data. This is know as sql injection. You should validate your email before doing your query at minimum.

Upvotes: 2

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

use this

     return true;
  }
 });
  ^^^ // you forgot this

Upvotes: 0

Related Questions