Validate field with ajax and php

Asked

Viewed 699 times

1

I am with a simple form, to validate if a name and email exist.

function valida_nome(){
	var filter_nome = /^([a-zA-Zà-úÀ-Ú0-9]|\s)+$/ ;
	if(!filter_nome.test(document.getElementById("input_nome_cad").value)){
	document.getElementById("input_nome_cad").value='';
	document.getElementById("input_nome_cad").placeholder = "Nome inválido";
	document.getElementById("input_nome_cad").style.borderColor = "#ff0000";
	document.getElementById("input_nome_cad").style.outline = "#ff0000";
	document.getElementById("input_nome_cad").focus();
	document.getElementById("input_nome_cad").onkeydown = function keydown_nome(){
	 	document.getElementById("input_nome_cad").style.borderColor = "#999999";
		document.getElementById("input_nome_cad").style.outline = null;
		}
		
	}
	
}
<!DOCTYPE html>
  <html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <title></title>
</head>
<body>
<script type="text/javascript" src="valida_ajax_js.js"></script>
<div id="Container">
  <h1>Agenda de Contatos utilizando AJAX</h1>
  <hr/>
  <h2>Pesquisar Contato:</h2>
  <form id="form_user_cad" name="form_user_cad" method="POST"  action="">
	<input type="text" id="input_nome_cad" name="nome_cad" placeholder="Nome e Sobrenome"    autofocus   onblur="valida_nome()"><br/>
	<input type="text" id="input_email_cad"	name="email_cad" placeholder="Insira o Email" ><br/>
	<input type="submit" class="btn_enviar_cad"	 name="enviar_cad"  value="Criar Conta">
   </form>
  </div>
 </body>
</html>

If you try to enter any of the special characters you will see that it is not possible.

So far it is exactly as I want, because the user can not advance to another field until filling correctly the field.

Next, the Ajax code to verify that the name that was correctly typed already exists, if it does not exist, you can proceed to the next field, but if it exists I want it to have the same behavior of character verification, ie the user can not advance.

Ajax code

function CriaRequest() {
	try{
	request = new XMLHttpRequest();        
	}catch (IEAtual){
		try{
        request = new ActiveXObject("Msxml2.XMLHTTP");       
        }catch(IEAntigo){
        	try{
            request = new ActiveXObject("Microsoft.XMLHTTP");          
            }catch(falha){
             request = false;
            }
        }
    }
    if (!request) 
    alert("Seu Navegador não suporta Ajax!");
    else
    return request;
}
function nome_existe() {
	var nome = document.getElementById("input_nome_cad").value;
	var xmlreq = CriaRequest();
	xmlreq.open("GET", "mysqli_select_ajax.php?nome_cad=" + nome, true);
	xmlreq.onreadystatechange = function(){
		if (xmlreq.readyState == 4) {
	    	if (xmlreq.status == 200) {
		    document.getElementById("input_nome_cad").value="";
		    document.getElementById("input_nome_cad").placeholder = xmlreq.responseText;
		    document.getElementById("input_nome_cad").style.borderColor = "#ff0000";
			document.getElementById("input_nome_cad").style.outline = "#ff0000";
			return true;
			}
		}
	};
	xmlreq.send(null);
}

And the bank code with php

<?php
// Verifica se existe a variável txtnome
if (isset($_GET["nome_cad"])) {
    $nome = $_GET["nome_cad"];
    // Conexao com o banco de dados
    $server = "localhost";
    $user = "root";
    $senha = "";
    $base = "bd_";
	
	$con = mysqli_connect($server, $user, $senha, $base);
	
	// Check connection
	if (mysqli_connect_errno())
  	{
  	echo "Failed to connect to MySQL: " . mysqli_connect_error();
  	}
	
	if (!empty($nome)) {
       $sql = "SELECT * FROM usuarios WHERE nome_cad like '$nome' ";
    }else{
	echo "Insira um nome";
	return;
	}   
    
    $result = mysqli_query($con, $sql);
    $linha = mysqli_fetch_assoc($result);
    if($linha['nome_cad'] != $nome ){        
    	echo $nome;
    }else {
        // Se a consulta não retornar nenhum valor, exibi mensagem para o usuário
        echo "Nome já existe!";
    }
} 
?>

Doubt

As I join the function valida_name() with the Ajax function, so that the function name_exists() is initialized after the 1st check has been performed and from the "onblur" input name="name_cad"?

The database file is ok, and the ajax tmb, because if I separate them from this function valida_name, they work well, make the check and if you have the name in the bank it warns, if it does not return the name typed.

The same problem is to join them to work in the above mentioned sequence.

1 answer

1


Add a return false, if it is not valid, and return true if valid:

function valida_nome(){
    var filter_nome = /^([a-zA-Zà-úÀ-Ú0-9]|\s)+$/ ;
    if(!filter_nome.test(document.getElementById("input_nome_cad").value)){
        document.getElementById("input_nome_cad").value='';
        document.getElementById("input_nome_cad").placeholder = "Nome inválido";
        document.getElementById("input_nome_cad").style.borderColor = "#ff0000";
        document.getElementById("input_nome_cad").style.outline = "#ff0000";
        document.getElementById("input_nome_cad").focus();
        document.getElementById("input_nome_cad").onkeydown = function keydown_nome(){
            document.getElementById("input_nome_cad").style.borderColor = "#999999";
            document.getElementById("input_nome_cad").style.outline = null;
        }
        return false;
    }
    return true;
}

Then in the nome_existe() You can put this right in the opening:

function nome_existe() {
    if(!valida_nome()) { // caso seja inválido
       alert('Nome Invalido');
       return;
    }
    ...
}

And, if I understood correctly in onblur of the input gets:

onblur="nome_existe()"
  • Opsss, periii, tho ver..

  • I think it gave belooo, thô just set up right here....

  • Note 10 Perfect.... Vlw ;)

  • You’re welcome @Magichat ..

Browser other questions tagged

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