How to add invalid status in html input fields?

0

I am doing validations in the database before the user submits the form, however, let's say the typed email already exists in the database, as I could mark the input field as invalid so that the user can not send if the current value of input is not changed?

Note: I say by invalid the validation of the HTML API itself, for example a input field not corresponding to pattern="" .

    
asked by anonymous 15.05.2018 / 15:38

2 answers

3

It is not possible to check the emails in the database only using the "HTML API" ( pattern="" ), WEB communication is done via HTTP, p>

You will need to do this using Ajax for example:

function validateEmail(field)
{
    //Se o campo estiver vazio ou desabilitado então não valida
    if (field.value == "" || field.disabled) return;

    field.disabled = true;

    var xhr = new XMLHttpRequest;

    xhr.open("GET", "checkEmail.php?email=" + encodeURIComponent(emailField.value), true);

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
               if (xhr.responseText == 'disponivel') {
                   alert('Validou');
               } else {
                   alert('Não validou');
               }
            } else {
                alert('Erro HTTP: ' + xhr.status);
            }
        }
    }

    xmlhttp.send(null);
}

HTML should be something like:

<form>
    <input type="email" pattern="[^@]@[^@]$" required onblur="validateEmail(this)">
    <button>Cadastrar</button>
</form>

In the php (it seems that is what you use) would just return a string as 'available' if the email does not exist in the database, or return anything else already exists, an example with mysqli :

checkEmail.php

<?php
if (empty($_GET['email'])) {
    die('email vazio');
}

$email = $_GET['email'];

if (!preg_match('#^[^@]+[@][@]+$#', $email)) {
    die('formato inválido');
}

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = 'SELECT COUNT(*) as total FROM tabela WHERE email=?';

$stmt = $mysqli->prepare($query);

$stmt->bind_param('s', $email);

$stmt->execute();

$stmt->bind_result($total);

while ($stmt->fetch()) {
    if ($total > 0) {
        echo 'já cadastrado';
    } else {
        echo 'disponivel';
    }
}
    
15.05.2018 / 16:06
1

I made an example to check if what the user already typed is equal to the value of the bank.

$.getJSON('emailbdvalue.php', function (data) {
   email = data.dado.email;  // aqui tráz o email cadastrado no banco

   $("#email").on("blur", function() { // função quando o usuário tira o foco do input
   valida = $(this).val(); // pega o que foi digitado pelo usuário

       if(valida != email || valida == "") {		
          $("#email").prop("disabled", false);
       }
       else {
	      $("#email").prop("disabled", true);
       }
   })
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>E-mail:<inputtype="email" id="email">
    
15.05.2018 / 15:50