I am doing the validations for the fields of my form, and one of these, is that if the value written in a field, in this case rut_usu is in the database, it is blocked the form, and self-approach the input again to modify its value. I'm doing it this way, look up the value correctly, and it shows me the right message, but how could I get the form blocked, if a result is found?
Javascript
$("#rut_usu").focusout(function(){
$("#resultado").removeClass("hide");
//obtenemos el texto introducido en el campo
var parametros = {"rut_usu" : $("#rut_usu").val()};
//hace la búsqueda
$.ajax({
type: "post",
url: '<?php echo base_url();?>C_Usuarios/consultar_rut',
data: parametros,
dataType: "html",
error: function(){
alert("error petición ajax");
},success: function(data){
if(data){
$('#btn_insert').attr('disabled', 'disabled');
$('#resultado').html('<span style="color:red;">Ya existe un usuario con ese Rut</span>');
window.document.r_usuarios.rut_usu.focus();
window.document.r_usuarios.rut_usu.select();
return false;
}
else{
$("#resultado").addClass("hide");
}
return true;
}
});
});
HTML
<div class="col-md-2">
<div class="form-group">
<label>Rut</label>
<input type="text" id="rut_usu" name="rut_usu" class="form-control" placeholder="18811942-5" autofocus>
<div id="resultado"></div>
</div>
</div>
If there is an equal value in the database, the message of the model is shown inside the result div.
Model
public function consultar_rut($rut_usu){
$query = $this->db->query("SELECT rut_usu FROM usuarios WHERE rut_usu='$rut_usu'");
$usuario = $query->row();
if(empty($usuario)) {echo false;} //Si existe devolvemos false
else {echo true; }//Si no existe, true.
}
EDITED
One of the people in the community, has helped me, to find part of the answer (uncheck it as accepted because I have not been able to solve an aspect within the question). Within javascript I also have the following to validate that a field is not blank:
$("#pnombre").focusout(function(){
if($("#pnombre").val().length<1){
$("#pnombre").addClass("blanco");
$("#msg_pnom").removeClass("hide");
window.document.r_usuarios.pnombre.focus();
window.document.r_usuarios.pnombre.select();
return false;
}
return true;
});
$("#pnombre").keypress(function(){
$("#pnombre").removeClass("blanco");
$("#msg_pnom").addClass("hide");
});
With this I am doing that if the field #pnombre is out of focus, if it is empty, the form is blocked and auto-focuses, if I add the lines with windows.id_form.id_campo and its attributes, when trying to validate the field #rut_usu does not auto-focus me, and the form fields are not blocked. If I enter a value of #rut_usu that is in the database, and then click on another field, which has windows validation, id_form etc. it auto-focus in that field even if the message is displayed, however if I click outside the form and not in another field, if it focuses #rut_usu. Example: