How to add invalid status in html input fields?

Asked

Viewed 500 times

0

I am making validations in the database before the user sends the form, however, let’s say that the e-mail already exists in the database, as I could mark the field input as invalid so that the user cannot send if the current value of the input?

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

validação usando API HTML

  • in back php and front html+js.

  • Although the answers are clear about the suggestions and recommendations, the problem is not related to whether it already exists, the problem is only to mark the field as invalid as for example in the image that upei.

2 answers

3

Is not possible check emails in the database only using the "HTML API" (pattern=""), in WEB communication is all done via HTTP, so you need a request.

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);
}

In HTML it should be something like:

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

In php (it seems that’s what you use) just return a string as 'available' random email does not exist in the bank, or return anything else chance 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';
    }
}
  • It’s almost that, actually what I need this precisely from that point you answered, if for example, I know that the email 'already registered', I want to mark the field as invalid, so that the user can not send the form.

1

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

$.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:
<input type="email" id="email">

  • urldobanco? Is not making a mess?

  • He does not want to check if what the user typed in the input is not the same as what is in the database?

  • I am quite sure that database has no URL, what exists is a back-end script that accesses a database and then the database via TCP, returns the data to the script, the script returns to the output and this output is downloaded to the browser of the user who made the related HTTP request.

  • It was a way to express face, logical that he will have to process the information of the bank either with PHP, or any other language, what I meant is that here comes the return of the bank with the information of the email.

  • 1

    I understood the suggestion @Leandro this way is interesting too, but it is your script does not mark the field as invalid.

  • Opa @Jeanfreitas I re-read the logic here and edited the answer, if you want to try it yet.

Show 1 more comment

Browser other questions tagged

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