Validate field with ajax and php

1

I have 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 type any of the special characters you will see that it is not possible.

So far this is exactly how I want it, because the user can not move to another field until the field is filled in correctly.

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

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!";
    }
} 
?>

A doubt

p>

The bank file is ok, and ajax tmb, because if I separate them from this function validate_name, they work fine, do the check and if it has the name in the bank it warns, otherwise it returns the name you typed.

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

    
asked by anonymous 06.06.2016 / 23:52

1 answer

1

Add a return false , if it is not valid, and return true if it is 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 nome_existe() you can put this in the opening:

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

And, if I understood correctly the onblur of the input is:

onblur="nome_existe()"
    
07.06.2016 / 00:02