How to verify that the email is registered when typing in the form?

Asked

Viewed 2,285 times

2

I have a registration form, and I’d like you to let me know, as soon as the email was typed, if it’s already in the database.

I thought to use a Javascript function, with a PHP code inside that will search if there is email in the Bank, but I’m not sure if it is possible to use PHP inside Javascript, someone has this information and otherwise, it is possible to use only Javascript for this?

  • 1

    Study about AJAX.

  • I think the most recommended would be an ajax request, within a Function Blur (Jquery) in the email field.. study these two techniques

  • See my answer to the step-by-step how to do Ajax with Javascript only. Don’t forget to mark the answer if it helped you. Big hug!

2 answers

9


It is possible to do only with Javascript?

It is not possible to do this only with Javascript, as you require access to the database to verify that the record exists. That is, some language should be executed on the server side - nothing prevents it from being also Javascript, such as Nodejs, but it would be in a different context.

You can use PHP inside Javascript?

No. This is one of the most basic concepts of the web and many people do not understand it correctly. PHP will run on the server side and Javascript on the client side. The only way they both communicate is through messages. The format of the message may vary depending on the protocol used, but the most common is HTTP. If you need to submit a Javascript value to PHP, you accurate send an HTTP request to the server. If you want PHP to return some value to Javascript, you accurate send them via the HTTP response that will be generated on the server.

I describe a little bit of this context here: How to write values to the Mysql database using PHP?

So how to proceed?

You should work on both fronts: Javascript and PHP. As Javascript, you should:

  1. Monitor the value of the email field in HTML by checking when there are changes in value;
  2. Check if the typed email is valid before making the request to the server;
    • If you request without validating the email, you will be demanding unnecessary network resources;
  3. When e-mail is valid, make a GET request to the server;
    • GET request is important for maintaining application semantics: you want to get a server state from base values;
  4. If the request is successful, check the body of the response;
  5. If the request fails, you should inform that if the email already exists, the registration will fail - or not allow the person to register at this time, since the server may be in trouble;

So in the code, we can have something similar to:

const email = document.getElementById("emailInput");
const button = document.getElementById("registerButton");
const messages = document.getElementById("messages");

function validate(email) {
  // Implemente a função de validar e-mail aqui
  return true;
}
      
email.addEventListener("input", function (event) {
  if (this.validity.valid || validate(this.value)) {
    fetch(`verifica.php?email=${this.value}`)
      .then(response => {
        if (response.ok) {
          return response.json();
        }
        throw new Error("Oops! Algo de errado não está certo...");
      })
      .then(json => {
        if (json.exists) {
          messages.innerHTML += `E-mail já está cadastrado. Por favor, tente outro.`;
        } else {
          messages.innerHTML += `E-mail disponível.`;
          button.disabled = false;
        }
      })
      .catch(error => {
        messages.innerHTML += `Falha no servidor, por favor, tente novamente mais tarde.`;
      });
  }
});
<form action="cadastrar.php" method="POST">
  <input id="emailInput" type="email" name="email" placeholder="Entre com o seu e-mail" required>
  <button id="registerButton" type="submit" disabled>Cadastrar</button>
  <div id="messages"></div>
</form>

Considerations on the code:

  1. I did not implement the function of validating e-mail not to extend the code too much and for this to be easily found on the web;
  2. I also used the email.validity to compose the check;
  3. I used the event input, because this, theoretically, is triggered to any input event that can modify the value of the field, either via mouse, keyboard or touch; for more accurate application behavior, it is important that you manually set all desired events, since browsers still do not strictly follow the W3C or WHATWG specification in this issue;
  4. To request I used the API fetch; is experimental and the future replacement for XMLHttpRequest, but works very well using the polyfill;
  5. I start the application with the disabled button and only enable it when the email is verified and available. This avoids that the user makes unnecessary requests to the server, with invalid or existing email, increasing the performance of the application and improving usability;
  6. If the request for verification fails, for any reason, I leave the button disabled to prevent the user to register, because I assume that, if there was an error with the verification, will occur, also, with the registration, then I warn the user of this embarrassing situation;

Already, on the server side, with PHP, you should:

  1. Check if the current request is a GET request;
  2. Check if the e-mail value has been correctly informed;
  3. Connecting to the database;
  4. Check the existence of the e-mail in the database table;
  5. Produce the response to be sent to the customer (browser);
  6. Effectively send the reply;

The code would be something like:

<?php

header('Content-Type: application/json');

try {
    if ($_SERVER['REQUEST_METHOD'] != 'GET') {
        throw new Exception("Não é uma requisição GET");
    }

    $email = filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL);

    if (!$email) {
        throw new Exception("O e-mail informado não é um e-mail válido");
    }

    $mysqli = require("db.php");
    $stmt = $mysqli->prepare("SELECT EXISTS(SELECT 1 FROM emails WHERE email = ?) as `exists`");
    $stmt->bindParam(1, $email); 
    $stmt->execute();
    $stmt->bind_result($row);

    if ($stmt->fetch()) {
        http_response_code(200);
        $output = $row;
    }
} catch (Exception $e) {
    http_response_code(500);
    $output = ['error' => $e->getMessage()];
} finally {
    echo json_encode($output);
}

So, if all goes well, PHP will return a JSON response in the format below, with the value 0 if the email is not registered or 1, otherwise with the status code of the response 200:

{exists: 0}

However, if any error occurs in the process, the response will have code 500 and a body stating the error message:

{error: 'O e-mail informado não é um e-mail válido'}

4

Yes, it is only possible with Javascript via Ajax (without loading jQuery).

HTML:

Put a oninput in the field where the e-mail will be typed calling the function that will send the e-mail to the PHP file to be consulted:

<input type="email" oninput="checaEmail(this.value)" />

Javascript:

Create two functions, one to do Ajax and the other to check if the e-mail that was typed is valid. Once the email is valid, as you type, Ajax will take action sent a request to the file verifica.php (you can use any file name you want, just change in the code below):

// cria a requisição XMLHttpRequest()
var http = false;
if(navigator.appName == "Microsoft Internet Explorer") {
    http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
    http = new XMLHttpRequest();
}

// função que verifica o campo digitado e faz o Ajax
function checaEmail(email){

   if(checkMail(email)){
      url_="verifica.php?email="+email;
      http.open("GET",url_,true);
      http.onreadystatechange=function(){
         if(http.readyState==4){
            if(http.responseText == "ok"){
               alert("email existe!");
            }else{
               alert("email não existe!");
            }
         }
      }
      http.send(null);
   }

}

// função para verificar validade do e-mail
function checkMail(email) {

    invalidChars = " ~\'^\`\"*+=\\|][(){}$&!%/:,;ç";

    if (email == "") {
        return false;
    }

    for (i=0; i<invalidChars.length; i++) {
        badChar = invalidChars.charAt(i);
        if (email.indexOf(badChar,0) > -1) {
            return false;
        }
    }

    lengthOfEmail = email.length;
    if ((email.charAt(lengthOfEmail - 1) == ".") || (email.charAt(lengthOfEmail - 2) == ".")) {
        return false;
    }

    Pos = email.indexOf("@",1);
    if (email.charAt(Pos + 1) == ".") {
        return false;
    }

    while ((Pos < lengthOfEmail) && ( Pos != -1)) {
        Pos = email.indexOf(".",Pos);
        if (email.charAt(Pos + 1) == ".") {
            return false;
        }
        if (Pos != -1) {
            Pos++;
        }
    }

    atPos = email.indexOf("@",1);
    if (atPos == -1) {
        return false;
    }

    if (email.indexOf("@",atPos+1) != -1) {
        return false;
    }

    periodPos = email.indexOf(".",atPos);
    if (periodPos == -1) {
        return false;
    }

    if (periodPos+3 > email.length) {
        return false;
    }
    return true;
}

PHP file:

In the PHP file you should check in the database if the email exists and return the string "ok" by issuing a alert in the Javascript above (this you can change to do as you like):

<?php
   $email = $_GET['email'];

   if(isset($email)){

      $conexao = mysqli_connect('host do BD', 'usuário', 'senha', 'nome do BD');
      $buscar = "select email from tabela where email='$email'";
      $query = $conexao->query($buscar);
      $numrow = mysqli_num_rows($query);
      if($numrow > 0){
         echo 'ok';
      }
   }
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.